Reputation: 247
I have three two classes
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*/
}
}
I want to modify this so that, A.1() should wait until X is set/modified in Class B. This is what my approach is:
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();
}
}
I am not sure why this is not working, as it puts both the thread on wait. I expected waitforSet()
function should have put calling thread on wait and internal will continue setting X. When i checked the currentthread's managed thread id in waitforSet()
and B.1()
they are different.
Can someone tell me what i am missing here or better way to achieve this?
P.S: I am achieving this in C#
Upvotes: 0
Views: 597
Reputation: 2768
I created this and it working normally, are you sure you are setting the initial state of AutoResetEvent to false in the constructor ?
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...");
}
}
Upvotes: 1