35
1
using System;
2
using System.Threading;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
Func<int, int, int> funcDelegate = (int num1, int num2) =>
9
{
10
Console.WriteLine($"Test method begins in thread {Thread.CurrentThread.ManagedThreadId}");
11
12
Thread.Sleep(TimeSpan.FromSeconds(3));
13
14
return num1 + num2;
15
};
16
17
IAsyncResult asyncResult = funcDelegate.BeginInvoke(30, 20, null, null);
18
19
Console.WriteLine($"Main thread {Thread.CurrentThread.ManagedThreadId} does some work.");
20
21
Thread.Sleep(TimeSpan.FromSeconds(2));
22
23
//Wait main thread for the child thread
24
asyncResult.AsyncWaitHandle.WaitOne();
25
26
Console.WriteLine("You can do other operations");
27
28
asyncResult.AsyncWaitHandle.Close();
29
30
//This wil return result without delay. Because, WaitOne() lets finishing child operation.
31
int result = funcDelegate.EndInvoke(asyncResult);
32
33
Console.WriteLine($"DoWork(30, 20) returned {result}");
34
}
35
}
Cached Result
Cat
Dog
Fish
Frog
Turtle
Snake
Chicken
Cow
Horse
Dog
Fish
Frog
Turtle
Snake
Chicken
Cow
Horse