簡體   English   中英

C#中的AutoResetEvent()

[英]AutoResetEvent() in C#

我有三個兩節課

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()應該等到X在類B中設置/修改。這就是我的方法:

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()函數應該已經將調用線程置於等待狀態,並且內部將繼續設置X。當我在waitforSet()B.1()檢查了當前線程的托管線程ID時,它們是不同的。

有人可以告訴我我在這里缺少什么,或者更好的方法來實現這一目標嗎?

PS:我正在用C#實現

我創建了它並且它正常工作,您確定要在構造函數中將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...");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM