int Main()
{
var task = Task.Run<int>(() =>
{
int sum = 0;
for (int i = 0; i < 10; i++)
{
sum += i;
Thread.Sleep(1000);
}
return sum;
});
int count=0;
while (!task.IsCompleted)
{
Console.WriteLine("等待异步任务:" + count + "秒");
count++;
Thread.Sleep(1000);
}
Console.WriteLine("任务完成,结果为" + task.Result);
static void Main(string[] args)
{
//Method1();
//Method2();
var task = Get1To10();
int count = 0;
while (!task.IsCompleted)
{
Console.WriteLine("等待异步任务:" + count + "秒");
count++;
Thread.Sleep(1000);
}
Console.WriteLine("任务完成,结果为" + task.Result);
}
public static async Task<int> Get1To10()
{
var taskResult = await Task<int>.Run<int>(() =>
{
int sum = 0;
for (int i = 0; i < 10; i++)
{
sum += i;
Thread.Sleep(1000);
}
return sum;
});
return taskResult;
}
这两段代码有什么区别,运行结果是两段代码都一样
如果可以用第一段代码完成任务,那么await又有什么用
可能你理解有误,并不需要用while等待结果的完成,看下面的例子, async和await就是一种语法糖 http://blog.jobbole.com/85787/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
namespace TestApp
{
}