加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#多线程编程:AutoResetEvent

发布时间:2020-12-15 22:40:42 所属栏目:百科 来源:网络整理
导读:作用 简单的完成多线程同步,两个线程共享相同的 AutoResetEvent 对象。线程可以通过调用 AutoResetEvent 对象的 WaitOne() 方法进入等待状态当第二个线程调用 Set() 方法时,它会解除对等待线程的阻塞。 原理 AutoResetEvent 在内存中维护一个布尔变量。如

作用

简单的完成多线程同步,两个线程共享相同的AutoResetEvent对象。线程可以通过调用AutoResetEvent对象的WaitOne()方法进入等待状态当第二个线程调用Set()方法时,它会解除对等待线程的阻塞。

原理

AutoResetEvent在内存中维护一个布尔变量。如果布尔变量为false,则它会阻塞线程,如果布尔变量为true,则取消阻塞线程。当我们实例化一个AutoResetEvent对象时,我们在构造函数中指定阻塞。下面是实例化AutoResetEvent对象的语法。

AutoResetEvent autoResetEvent = new AutoResetEvent(false);

?

使用WaitOne方法等待其他线程

此方法阻塞当前线程并等待其他线程的信号。WaitOne方法将当前线程置于Sleep状态。如果WaitOne方法收到信号则返回true,否则返回false

autoResetEvent.WaitOne();

?也可以使用WaitOne的重载方法来指定等待的时间,到达等待时间仍然没有接收到信号则放弃等待继续执行后续操作。

static void ThreadMethod()
{
    while(!autoResetEvent.WaitOne(TimeSpan.FromSeconds(2)))
    {
        Console.WriteLine("Continue");
        Thread.Sleep(TimeSpan.FromSeconds(1));
    }
 
    Console.WriteLine("Thread got signal");
}

我们通过传递2秒作为参数来调用WaitOne方法。在while循环中,等待2秒如果没有接收到信号则继续工作。当线程得到信号时,WaitOne返回true并退出循环,打印“Thread got signal”

使用Set方法设置信号

AutoResetEventSet方法将信号发送到等待线程以继续其工作。下面是调用Set方法的语法。

autoResetEvent.Set();

完整过程示例

class Program
{
    static AutoResetEvent autoResetEvent = new AutoResetEvent(false);
    static string dataFromServer = "";
 
    static void Main(string[] args)
    {
        Task task = Task.Factory.StartNew(() =>
        {
            GetDataFromServer();
        });
 
        //Put the current thread into waiting state until it receives the signal
        autoResetEvent.WaitOne();
 
        //Thread got the signal
        Console.WriteLine(dataFromServer);
    }
 
    static void GetDataFromServer()
    {
        //Calling any webservice to get data
        Thread.Sleep(TimeSpan.FromSeconds(4));
        dataFromServer = "Webservice data";
        autoResetEvent.Set();
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读