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

相关文章:

  • 2021-09-25
  • 2021-11-08
  • 2021-12-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-12
  • 2021-08-26
猜你喜欢
  • 2021-09-11
  • 2021-11-10
  • 2021-12-09
  • 2021-07-07
  • 2021-06-23
  • 2022-12-23
相关资源
相似解决方案