c#

C#多线程等待回调

2017-02-25  本文已影响274人  么么gou的偷

此处介绍一下 AutoResetEvent的方法

下面贴一下微软自带的一个方法。

using System;
using System.Threading;

class ZLP_TEST
{
    static AutoResetEvent autoEvent = new AutoResetEvent(false);

    static void Main()
    {
        Console.WriteLine("Main starting.");

        ThreadPool.QueueUserWorkItem(
            new WaitCallback(WorkMethod), autoEvent);

        // Wait for work method to signal.
        autoEvent.WaitOne();
        Console.WriteLine("Work method signaled.\nMain ending.");
        Console.ReadKey();
    }

    static void WorkMethod(object stateInfo) 
    {
        Console.WriteLine("Work starting.");

        // Simulate time spent working.
        Thread.Sleep(10000);
        
        // Signal that work is finished.
        Console.WriteLine("Work ending.");
        ((AutoResetEvent)stateInfo).Set();
    }
}

这样点击后就是

Paste_Image.png

sleep十秒后

Paste_Image.png

我们会注意到里面有个方法

ThreadPool.QueueUserWorkItem(
            new WaitCallback(WorkMethod), autoEvent);

此处这个方法可以替换带参数启动一个new Thread。 上面这个方法已经非常简练,建议这么使用,下面这个方法挺繁琐的。
下面的方法其实也是带参数新建线程的一个方法。

我们先新建一个类

public class Test
        {
            AutoResetEvent autoEvent;
            public Test(AutoResetEvent autoevent)
            {
                autoEvent = autoevent;
            }
            public void WorkMethod()
            {
                Console.WriteLine("Work starting.");

                // Simulate time spent working.
                Thread.Sleep(10000);

              
                // Signal that work is finished.
                Console.WriteLine("Work ending.");
                ((AutoResetEvent)autoEvent).Set();
            }

        }

那么将原先工程中的替换一下

using System;
using System.Threading;

class ZLP_TEST
{
    static AutoResetEvent autoEvent = new AutoResetEvent(false);

    static void Main()
    {
        Console.WriteLine("Main starting.");
        //原先的做法
        //ThreadPool.QueueUserWorkItem(
           // new WaitCallback(WorkMethod), autoEvent);
        //目前的做法
            Test a = new Test(autoEvent);
            Thread b = new Thread(new ThreadStart(a.WorkMethod));
            b.Start();
        // Wait for work method to signal.
        autoEvent.WaitOne();
        Console.WriteLine("Work method signaled.\nMain ending.");
        Console.ReadKey();
    }

    static void WorkMethod(object stateInfo) 
    {
        Console.WriteLine("Work starting.");

        // Simulate time spent working.
        Thread.Sleep(10000);
        
        // Signal that work is finished.
        Console.WriteLine("Work ending.");
        ((AutoResetEvent)stateInfo).Set();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读