关于Async / Await的澄清

时间:2016-12-08 18:09:03

标签: c# .net async-await

我在async / await上阅读过的许多教程都觉得它们太过复杂了概念。理想情况下,当调用方法继续其业务时,它将允许在后台运行一些耗时的任务。

我决定创建一个我能想到的最简单的async / await示例。 C#控制台应用程序:

class Program
{
    static void Main(string[] args)
    {

        PrintTwoTimes();

        Console.WriteLine("Main Method!");

        Console.ReadLine();
    }

    async static Task PrintTwoTimes()
    {
        await Task.Run(() =>
        {
            Thread.Sleep(500);
            Console.WriteLine("Inside Async Task!");
        });

        Console.WriteLine("After Async Task!");
    }
}

输出符合我的预期。

Output

调用线程继续执行而不等待PrintTwoTimes()完成。

我想知道的是,在现实世界中,像我所做的那样简单的异步/等待方法有什么危险?

* 编辑 *

在被告知我的问题是愚蠢的之后,我正在删除有关静态的内容并添加删除它的更新代码

class Program
{
    static void Main(string[] args)
    {
        //call the async thread
        var prtclss = new PrintClass();

        prtclss.PrintTwoTimes();

        Console.WriteLine("Main Method!");

        Console.ReadLine();
    }


}

class PrintClass
{
    public string str1 { get; set; }
    public string str2 { get; set; }

    public PrintClass()
    {
        str1 = "Inside Async Task!";
        str2 = "After Async Task!";
    }

    public async Task PrintTwoTimes()
    {
        await Task.Run(() =>
        {
            //simulate time consuming task
            Thread.Sleep(500);
            Console.WriteLine(str1);
        });

        Console.WriteLine(str2);

    }


}

0 个答案:

没有答案