【发布时间】: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() 的方式重要吗?还是我错过了什么?
谁能帮帮我?或指出我的错误。
谢谢。
【问题讨论】:
-
编译器会给你警告,告诉你你的
async方法将同步运行,因为你不使用await。我有一个asynctutorial,您可能会觉得有帮助。
标签: c# .net asynchronous console-application c#-5.0