【问题标题】:How to run method that use 'async Task' key word asynchronously?如何异步运行使用“异步任务”关键字的方法?
【发布时间】:2016-07-01 09:27:01
【问题描述】:

我想我可以在调用它之后异步运行使用'async Task'方法的方法,但是它被阻塞了,实际上它是同步运行的,见我的代码如下。

    static void Main(string[] args)
    {
        asyncTest();// use asyncTest.Wait() help nothing. 
        Console.ReadKey();
    }

    static async Task asyncTest() 
    {
        Console.WriteLine("before init task second " + DateTime.Now.Second);
        var t1 = getInt1S();// I supposed it to run background,but it blocked
        var t3 = getInt3S();
        //var await1 = await t1;//this line just no use, run quickly
        //var await3 = await t3;//this line just no use, run quickly
        Console.WriteLine("after init task second " + DateTime.Now.Second);
    }

    static async Task<int> getInt1S() 
    {
        Console.WriteLine("getInt1S" + DateTime.Now.Second);
        Task.Delay(1000).Wait();
        return 1;
    }

    static async Task<int> getInt3S() 
    {
        Console.WriteLine("getInt3S" + DateTime.Now.Second);
        Thread.Sleep(3000);
        return 3;
    }

输出如下:

before init task second 21
getInt1S 21
getInt3S 22
after init task second 25

为什么 'getInt1S()' 和 'await getInt3S()' 都同步运行?有没有办法像这样编码:

var a = methodSync();//method define like: async Task<T> methodSync()
Console.Write("");//do something during processing the methodSync
T b = await a;

我不会知道如何在 ConsoleApp 中使用 'async methodSync()'。只是如何让我的 't1' 和 't2' 在 'asyncTest()' 中异步运行。

我正在处理 async/await,所以我想找到与 ' var a = new Task(()=>{return 1;}) '不同的东西

调用 asyncTest() 的方式重要吗?还是我错过了什么?

谁能帮帮我?或指出我的错误。

谢谢。

【问题讨论】:

标签: c# .net asynchronous console-application c#-5.0


【解决方案1】:

所有异步方法同步运行,直到第一个 await 指令。

然后,如果 awaitable(await 等待的内容)完成,它将继续同步运行,直到下一条 await 指令或方法结束。

一旦到达未完成的可等待对象,控制权就会返回给返回 Task 的调用方法,该方法将在异步方法中的所有可等待对象都完成并到达方法结束时完成。

此编译器功能的目的是轻松生成按顺序(非同步)运行的代码,从而实现您所看到的。

【讨论】:

  • 我找到了。将 Task.Delay(1000).Wait() 和 Thread.Sleep(3000) 替换为 await Task.Delay(1000) 将异步运行 getInt1S() 和 getInt1S() .我知道每当创建一个任务时,系统都会在任务中同步运行所有代码,除非它被 await 指出。任务创建器将在闭包中同步运行所有代码对我来说是新的。
  • await 不会创建 Task
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
  • 1970-01-01
  • 2022-01-25
  • 2010-10-25
  • 2018-09-12
  • 1970-01-01
相关资源
最近更新 更多