C#中的AutoResetEvent()

时间:2012-07-11 05:20:15

标签: c# multithreading concurrency

我有三个两个班级

Class A{
   function A.1()
   {
     1. First calls B.2()
     2. Checks for value X in class B.
   }
}
Class B {
 function B.1()
 {
  /*this function sets the variable X to true*/
 }
 function B.2()
 {
   /*Initiates the thread eventually that will start the function B.1 on different thread*/
 }
}

我想修改它,以便A.1()应该等到在B组中设置/修改X.这就是我的方法:

Class A{
   function A.1()
   {
     1. First calls B.2()
     **2. Call WaitforSet in class B**
     3. Checks for value X in class B.
   }
}
Class B {
/* Created one autoreset event S*/
 function B.1()
 {
  /*this function sets the variable X to true*/
  S.Set();
 }
 function B.2()
 {
   /*Initiates the thread eventually that will start the function B.1 on different thread*/
 }
  waitforSet()
  {
   S.waitone();
  }
}

我不确定为什么这不起作用,因为它使两个线程都在等待。我期望waitforSet()函数应该将调用线程置于等待状态并且internal将继续设置X.当我在waitforSet()B.1()中检查currentthread的托管线程ID时,它们是不同的。

有人可以告诉我这里缺少什么或更好的方法来实现这个目标吗?

P.S:我在C#中实现了这个目标。

1 个答案:

答案 0 :(得分:1)

我创建了它并且它正常工作,你确定你在构造函数中将AutoResetEvent的初始状态设置为false吗?

class Program
{
    static void Main(string[] args)
    {
        Thread.CurrentThread.Name = "Console Thread";

        var a = new A();
        a.A1();

        Console.WriteLine("Press return to exit...");
        Console.Read();
    }
}

public class A
{
    public void A1()
    {
        var b = new B();

        b.B2();
        b.WaitForSet();

        Console.WriteLine("Signal received by " +  Thread.CurrentThread.Name + " should be ok to check value of X");
        Console.WriteLine("Value of X = " + b.X);
    }
}

public class B
{
    private AutoResetEvent S = new AutoResetEvent(false);

    public bool X { get; private set; } 

    public void B1()
    {
        X = true;
        Console.WriteLine("X set to true by " + Thread.CurrentThread.Name);

        S.Set();
        Console.WriteLine("Release the hounds signal by " + Thread.CurrentThread.Name);
    }

    public void B2()
    {
        Console.WriteLine("B2 starting thread...");

        var thread = new Thread(new ThreadStart(B1)) { Name = "B Thread" };
        thread.Start();

        Console.WriteLine("Value of X = " + X + " Thread started.");
    }

    public void WaitForSet()
    {
        S.WaitOne();
        Console.WriteLine(Thread.CurrentThread.Name + " Waiting one...");
    }
}