zoukankan      html  css  js  c++  java
  • C#:简单线程样例

    1、定义线程类及内部事件

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms;
    
    namespace ThreadSample
    {
        public delegate void ThreadEventHandler(object sender, EventArgs e);
        public class myThread
        {
            //线程执行开始调用事件
            public event ThreadEventHandler RequestEvent;
            //线程执行结束调用事件
            public event ThreadEventHandler CompletedEvent;
            //是否允许执行线程中具体任务
            public bool isExecute = false;
            //线程名称
            private string threadName = "线程";   //string.Empty;
            public string ThreadName
            {
                get { return threadName; }
            }
    
            public void Start()
            {
                try
                {
                    //执行前调用事件
                    RequestEvent(this, null);
                    if (isExecute)
                    {
                        //执行任务
                        Random seed = new Random(DateTime.Now.Millisecond);
                        int sleepTime = seed.Next(100, 300);
                        Thread.Sleep(sleepTime);
                    }
    
                    threadName += Thread.CurrentThread.ManagedThreadId.ToString();
    
                    //执行后调用事件
                    CompletedEvent(this, null);
                }
                catch (Exception ex)
                {
                    //记录错误日志追踪文件
                }
            }
        }
    }
    View Code

    2、在外部调用线程,并添加线程事件内容,及其监视器实现同步

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Threading;
    
    namespace ThreadSample
    {
        
    
        public partial class frmApp : Form
        {
            public frmApp()
            {
                InitializeComponent();
            }
    
            private void btnExit_Click(object sender, EventArgs e)
            {
                Environment.Exit(0);
            }
    
            private void btnRun_Click(object sender, EventArgs e)
            {
                try
                {
                    int threadCount = 10;
                    this.tbMonitor.Clear();      //显示监视线程的信息
                    myThread[] threadArray = new myThread[threadCount];
                    Thread td = null;
                    for (int i = 0; i < threadCount; i++)
                    {
                        threadArray[i] = new myThread();
                        threadArray[i].RequestEvent += frmApp_RequestEvent;
                        threadArray[i].CompletedEvent += frmApp_CompletedEvent;
                        td = new Thread(threadArray[i].Start);
                        td.Start();
                    }
                }
                catch (Exception ce)
                {
                    MessageBox.Show(ce.ToString());
                }
            }
    
            //记录线程信息
            private delegate void RecordsEventHandler(object sender, EventArgs e);
    
            //依据线程调用次方法的先后显示信息
            private void frmApp_CompletedEvent(object sender, EventArgs e)  //sender太泛,可以给准确名字(myThread)
            {
                if (this.tbMonitor.InvokeRequired)
                {
                    this.tbMonitor.Invoke(new RecordsEventHandler(frmApp_CompletedEvent), new object[] { sender, e });
                }
                else
                {
                    try
                    {
                        Monitor.Enter(this.tbMonitor);  //同步机制,指定对象获取排它锁
    
                        //具体操作
                        this.tbMonitor.Text += (sender as myThread).ThreadName + "--- ---" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffff ") + Environment.NewLine;
                    
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                        //记录错误日志追踪文件
                    }
                    finally
                    {
                        Monitor.Exit(this.tbMonitor);   //同步机制,指定对象释放排它锁
                    }
                }
            }
    
            private void frmApp_RequestEvent(object sender, EventArgs e)
            {
                //是否允许执行线程中具体任务
                (sender as myThread).isExecute = true;
            }
        }
    }
    View Code

    注意:监视器实现同步的对象是否必须调用Invoke()方法。

  • 相关阅读:
    子集和数问题——回溯法
    七言
    Java冒泡排序
    七言
    定义一个Collection接口类型的变量,引用一个Set集合的实现类,实现添加单个元素, 添加另一个集合,删除元素,判断集合中是否包含一个元素, 判断是否为空,清除集合, 返回集合里元素的个数等常用操作。
    创建Car类,包含name,price属性,构造器等方法,创建测试类,在main方法中创建Set接口的实现类,添加5个以上的Car对象,遍历集合元素,验证重复元素是否过滤了; 如果没有过滤,实现过滤功能;把每个小车的price降10000元,再遍历,查看price是否已改变
    20项素数和环——递归
    8项素数和环——枚举法
    填算式
    纵横放火柴
  • 原文地址:https://www.cnblogs.com/shenchao/p/4679777.html
Copyright © 2011-2022 走看看