CSharp · Console
using System;
using System.Threading;
public class Program
{
public static void Main()
{
Func<int, int, int> funcDelegate = (int num1, int num2) =>
{
Console.WriteLine($"Test method begins in thread {Thread.CurrentThread.ManagedThreadId}");
Thread.Sleep(TimeSpan.FromSeconds(3));
return num1 + num2;
};
IAsyncResult asyncResult = funcDelegate.BeginInvoke(30, 20, null, null);
Console.WriteLine($"Main thread {Thread.CurrentThread.ManagedThreadId} does some work.");
Thread.Sleep(TimeSpan.FromSeconds(2));
//Wait main thread for the child thread
asyncResult.AsyncWaitHandle.WaitOne();
Console.WriteLine("You can do other operations");
asyncResult.AsyncWaitHandle.Close();
//This wil return result without delay. Because, WaitOne() lets finishing child operation.
int result = funcDelegate.EndInvoke(asyncResult);
Console.WriteLine($"DoWork(30, 20) returned {result}");
}
}