您的位置:首页 > 编程语言 > C#

C#--async-await的用法

2016-08-04 19:54 543 查看
NET 中的 async/await 异步编程

MSDN上的文章

**async与await最佳实践

需要先理解thread的用法,再掌握task的用法,才能力理解async和await的用法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading;
using System.Threading.Tasks;

namespace TestApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("-------主线程启动-------");
Task<int> task = GetLengthAsync();
Console.WriteLine("Main方法做其他事情");
Console.WriteLine("Task返回的值" + task.Result);
Console.WriteLine("-------主线程结束-------");
}

static Task<int> GetLengthAsync()
{
Console.WriteLine("GetLengthAsync Start");
Task<int> task = Task<int>.Run(() => { string str = GetStringAsync().Result;
Console.WriteLine("GetLengthAsync End");
return str.Length; });
return task;
}

static Task<string> GetStringAsync()
{
return Task<string>.Run(() => { Thread.Sleep(2000); return "finished"; });
}
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: