简体   繁体   English

使用c#进行异步编程-async,await和Task.Run

[英]Asynchronous Programming with c# - async , await and Task.Run

class Program
{
    static void Main(string[] args)
    {
        AsyncWithWait();
        //Console.WriteLine(s.Result);
        Task.Run(() => AsyncWithOutWait());
        Console.WriteLine("Main End");
        Console.ReadLine();

    }
    public static void AsyncWithOutWait()
    {
        Thread.Sleep(3000);
        Console.WriteLine("AsyncWithOutWait");
    }

    public static async Task AsyncWithWait()
    {
        await Task.Delay(5000);
        Console.WriteLine("AsyncWithWait");
    }
}

Is there any difference between the way AsyncWithWait and AsyncWithOutWait in the above implementation? 在上面的实现中,AsyncWithWait和AsyncWithOutWait的方式之间有什么区别吗?

The output is as expected but I would like to know the proper way to implement Asynchronous programming. 输出是预期的,但我想知道实现异步编程的正确方法。

Output 产量

Main End
AsyncWithOutWait
AsyncWithWait

Is there any difference between the way AsyncWithWait and AsyncWithOutWait in the above implementation? 在上面的实现中,AsyncWithWait和AsyncWithOutWait的方式之间有什么区别吗?

AsyncWithWait doesn't block a thread just waiting for the time period; AsyncWithWait不会仅在等待时间段时阻塞线程。 AsyncWithOutWait does. AsyncWithOutWait做到了。

The output is as expected but I would like to know the proper way to implement Asynchronous programming. 输出是预期的,但我想知道实现异步编程的正确方法。

Use async and await . 使用asyncawait To understand more how it works, read my intro to async post. 要了解其工作原理,请阅读async介绍

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM