C#线程操作的各个方法(创建、挂起、终止、恢复、等待终止等)

C#线程操作的各个方法

 

    在UI事件后需要执行大量耗费时间的代码时,通常需要将此代码放入线程中去执行,本文着重讲一下从线程的创建到执行及终止的一系列操作。

一、线程的创建。

    线程创建分为带参数线程与不带参数线程,带参数时需要用object做封装,多个参数使用object[] data,以下为代码

// 无参数函数
public static void ParaMeterFreeMethod()
{
	Console.WriteLine("this is a not Parameter Fun");
}
// 带参数函数
public static void ParameterMethod(object data)
{
	string myRealData = data as string; // 拆箱操作
	Console.WriteLine("this is a have Parameter Method, the Para is: " + myRealData);
}

static void Main()
{
	Thread t1 = new Thread(ParaMeterFreeMethod);
	Thread t2 = new Thread(new ParameterizedThreadStart(ParameterMethod));
	t1.BackGround = true;
	t2.BackGround = true;
	t1.Start(); // 启动无参数线程
	t2.Start("hello thred"); // 启动带参数线程
}

二、线程的异步执行

在线程的异步执行中,主要使用两种方式,一种为创建委托使用BeginInvoke,看需求再看是否添加回调函数;第二种使用窗体中提供的一个封装类,BackgroundWoker类,在该类中已经对主操作和回调函数做了封装,只需要调用即可。

1、BackGroundWoker封装

class AsynThread
    {
        public BackgroundWorker bw = new BackgroundWorker();
        public AsynThread()
        {
            bw.DoWork += new DoWorkEventHandler(BwDoWork);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BwWorkCompleted);
        }


        private void BwDoWork(object sender, DoWorkEventArgs e)
        {
            for(int i = 0; i < 100; i++)
            {
                Console.WriteLine("background thread , value: " + i);
                Thread.Sleep(30);
            }
        }

        private void BwWorkCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Console.WriteLine("background thread finshed");
        }
    }
// 主函数中调用
static void Main()
{
	AsynThread myThead = new AsynThread();
        myThead.bw.RunWorkerAsync();
        AsynTheadBiginInvoke.DoWorkMethod(100);
        for(int i = 0; i < 50; i++)
        {
            Console.WriteLine("Main thread , value: " + i);
            Thread.Sleep(5);
        }
        Console.WriteLine("Main thread finished");
}

2、使用beginInvoke进行异步调用

delegate string MethodDelegate(int iCallTime);
    public static class AsynTheadBiginInvoke
    {
        public static string LongRunningMethod(int iCallTime)
        {
            for(int i = 0; i < iCallTime; i++)
            {
                Console.WriteLine("back thread , value: " + i);
                Thread.Sleep(50);
            }
            
            return "MyCallTime was:" + iCallTime.ToString();
        }

        public static void DoWorkMethod(int myTime)
        {
            MethodDelegate dlgt = new MethodDelegate(LongRunningMethod);
            AsyncCallback asyCallBack = new AsyncCallback(MethodCompleted);
            IAsyncResult iar = dlgt.BeginInvoke(20, asyCallBack, dlgt);
        }

        public static void MethodCompleted(IAsyncResult iar)
        {
            string str = null;
            MethodDelegate dlgt = (MethodDelegate)iar.AsyncState;
            str = dlgt.EndInvoke(iar);
            Console.WriteLine("long time work completed!");
        }
    }
static void Main(string[] args)
 {
            
     AsynTheadBiginInvoke.DoWorkMethod(100);
     for(int i = 0; i < 50; i++)
     {
        Console.WriteLine("Main thread , value: " + i);
        Thread.Sleep(5);
     }
     Console.WriteLine("Main thread finished");


     Console.ReadKey();
 }

此时执行主函数时,调用完DoWorkMethod()函数后马上执行后边的语句,执行完后会自动调用Methcompleted()方法,通过endInvoke拿到返回值,而若需要在执行beginInvoke就拿到值,需要将回调函数置为null,然后执行beginInvoke后线程会阻塞等待委托的函数执行完后,才执行后续的语句,包括主线程也会被阻塞

  • 8
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值