Reputation: 63
class Program
{
public delegate void ss(string s);
public static void print(string s)
{
Console.WriteLine("asynchronous thread..."+s+DateTime.Now.ToLongTimeString());
System.Threading.Thread.Sleep(3000);
}
static void Main(string[] args)
{
ss s = print;
Console.WriteLine("Main thread..." + DateTime.Now.ToLongTimeString());
IAsyncResult result = s.BeginInvoke("hello", null, null);
for (int i = 0; i < 50; i++)
{
Console.WriteLine("Main...thread..."+DateTime.Now.ToLongTimeString());
}
System.Threading.Thread.Sleep(3000);
Console.WriteLine("Main...thread...after sleep" + DateTime.Now.ToLongTimeString());
Console.WriteLine("Main...thread...after sleep..." + DateTime.Now.ToLongTimeString());
s.EndInvoke(result);
Output is:
Main thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
**asynchronous thread...hello 4:20:01 PM**
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
**Main...thread...after sleep4:20:04 PM**
**Main...thread...after sleep...4:20:04 PM**
My question is why sleep method doesn't count in asynchronous method?
Upvotes: 0
Views: 82
Reputation: 236218
My question is why sleep method doesn't count in asynchronous method?
It does encounter. After writing line asynchronous thread...hello 4:20:01 PM
your background thread goes to sleep, but main thread continues to print messages. Add message after background thread has awaken to see that Sleep worked:
public static void print(string s)
{
Console.WriteLine("async thread..." + s + DateTime.Now.ToString("T"));
System.Threading.Thread.Sleep(2000);
Console.WriteLine("async thread after sleep " + DateTime.Now.ToString("T"));
}
Upvotes: 1