关于异步编程的困惑

时间:2014-01-22 08:39:22

标签: c# .net asynchronous

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);

输出是:

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**  

我的问题是为什么睡眠方法不计入异步方法?

1 个答案:

答案 0 :(得分:1)

  

我的问题是为什么睡眠方法不计入异步方法?

确实遇到了。写入行asynchronous thread...hello 4:20:01 PM后,后台线程进入休眠状态,但主线程继续打印消息。在后台线程唤醒后添加消息以查看睡眠是否有效:

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"));
}