C#使用AutoResetEvent实现同步的详解及实例

黄舟
Release: 2017-03-28 11:10:42
Original
1485 people have browsed it

这篇文章主要为大家详细介绍了C#使用AutoResetEvent实现同步的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

前几天碰到一个线程的顺序执行的问题,就是一个异步线程往A接口发送一个数据请求。另外一个异步线程往B接口发送一个数据请求,当A和B都执行成功了,再往C接口发送一个请求。说真的,一直做BS项目,对线程了解,还真不多。就知道AutoResetEvent这个东西和线程有关,用于处理线程切换之类,于是决定用AutoResetEvent来处理上面的问题。

于是网上查找相关资料:

原来,AutoResetEvent在.Net多线程编程中经常用到。当某个线程调用WaitOne方法后,信号处于发送状态,该线程会得到信号, 程序就会继续向下执行,否则就等待。而且 AutoResetEvent.WaitOne()每次只允许一个线程进入,当某个线程得到信号后,AutoResetEvent会自动又将信号置为不发送状态,其他调用WaitOne的线程只有继续等待.也就是说,AutoResetEvent一次只唤醒一个线程,其他线程还是堵塞。

简介

AutoResetEvent(bool initialState):构造函数,用一个指示是否将初始状态设置为终止的布尔值初始化该类的新实例。
    false:无信号,子线程的WaitOne方法不会被自动调用
    true:有信号,子线程的WaitOne方法会被自动调用
 Reset ():将事件状态设置为非终止状态,导致线程阻止;如果该操作成功,则返回true;否则,返回false。
 Set ():将事件状态设置为终止状态,允许一个或多个等待线程继续;如果该操作成功,则返回true;否则,返回false。
 WaitOne(): 阻止当前线程,直到收到信号。
 WaitOne(TimeSpan, Boolean) :阻止当前线程,直到当前实例收到信号,使用 TimeSpan 度量时间间隔并指定是否在等待之前退出同步域。   
    WaitAll():等待全部信号。 

实现

 class Program
 {

  static void Main()
  {
   Request req = new Request();

   //这个人去干三件大事 
   Thread GetCarThread = new Thread(new ThreadStart(req.InterfaceA));
   GetCarThread.Start();

   Thread GetHouseThead = new Thread(new ThreadStart(req.InterfaceB));
   GetHouseThead.Start();

   //等待三件事都干成的喜讯通知信息 
   AutoResetEvent.WaitAll(req.autoEvents);

   //这个人就开心了。 
   req.InterfaceC();

   System.Console.ReadKey();
  }
 }

 public class Request
 {
  //建立事件数组 
  public AutoResetEvent[] autoEvents = null;

  public Request()
  {
   autoEvents = new AutoResetEvent[]
   {
    new AutoResetEvent(false),
    new AutoResetEvent(false)
   };
  }

  public void InterfaceA()
  {
   System.Console.WriteLine("请求A接口");

   Thread.Sleep(1000*2);

   autoEvents[0].Set();

   System.Console.WriteLine("A接口完成");
  }

  public void InterfaceB()
  {
   System.Console.WriteLine("请求B接口");

   Thread.Sleep(1000 * 1);

   autoEvents[1].Set();

   System.Console.WriteLine("B接口完成");
  }

  public void InterfaceC()
  {
   System.Console.WriteLine("两个接口都已经请求完,正在处理C");
  }
 }
Copy after login

注意,WaitOne 或是WaitAll 最好都加上超时时间。否则没有收到信号,线程一直会阻塞。 

后话

这个只是上面的场景的一个简化,主要是用来解决刚刚我说的那个场景的问题。
以上是自己对AutoResetEvent的使用总结。不足之处请各位指点一二。

The above is the detailed content of C#使用AutoResetEvent实现同步的详解及实例. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!