Long story short I have two boolean variables called FirstBool and SecondBool. I have a program which uses two delegates to run two methods asynchronously. I am using Console.ReadLine() to keep the parent thread alive while the child thread runs.
When the first method completes, FirstBool is set to true. When the second method completed, SecondBool is set to true.
Long story short, I want to define my event as “FirstBool and SecondBool are both true”, and close my program at this time. The only alternative I can see to this is to poll both boolean values until they are both true and then close the program, and polling sucks.
My code is below:
class Program
{
private delegate void MyDelegate();
private static bool FirstBool { get; set; }
private static bool SecondBool { get; set; }
static void Main(string[] args)
{
FirstBool = false;
SecondBool = false;
MyDelegate firstDelegate = new MyDelegate(FirstMethod);
MyDelegate secondDelegate = new MyDelegate(SecondMethod);
AsyncCallback myCallback = new AsyncCallback(CallbackMethod);
firstDelegate.BeginInvoke(myCallback, "Zip");
secondDelegate.BeginInvoke(myCallback, "Line");
Console.ReadLine();
}
private static void CallbackMethod(IAsyncResult result)
{
switch (result.AsyncState.ToString())
{
case "Zip":
FirstBool = true;
break;
case "Line":
SecondBool = true;
break;
}
Console.WriteLine("Callback Method");
}
private static void FirstMethod()
{
Console.WriteLine("First Method");
}
private static void SecondMethod()
{
Console.WriteLine("Second Method");
}
}
So, long story short, how do I create an event whose definition is “FirstBool is true and SecondBool is true” and run a method on this events occurence?
Thanks
If you have access to .NET 4, then you can very easily accomplish this with the Task Parallel Library:
If you’re using an older version of .NET, then you simply need to call the
EndInvokemethod to wait for the asynchronous calls to complete: