我想我可以运行在调用它之后异步使用'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(()=&gt; {return 1;})'
不同的内容调用asyncTest()的方式有用吗?或者我错过了什么?
任何可以帮助我的人?或者指出我的错误。
感谢。
答案 0 :(得分:2)
所有异步方法同步运行,直到第一个await
指令。
然后,如果等待(等待await
等待),它将继续同步运行,直到下一个await
指令或方法结束。
一旦达到未完成的等待状态,控件将返回到调用方法,返回Task
,当异步方法中的所有等待都完成并且到达方法结束时,该^((?:\D+(?:\d?\D*){0,7})|(?:[1-9]\D*(?:\d?\D*){0,6}))$
将完成。 / p>
此编译器功能的目的是轻松生成按顺序(非同步)运行的代码,因此,您所看到的。