异步和等待(async和await)

2018-01-27 19:12:17来源:cnblogs.com作者:飞飞兔人点击

分享

   在.Net 4.5中,通过async和await两个关键字,引入了一种新的基于任务的异步编程模型(TAP)。在这种方式下,可以通过类似同步方式编写异步代码,极大简化了异步编程模型。如下式一个简单的实例:

static async void DownloadStringAsync2(Uri uri)    {        var webClient = new WebClient();        var result = await webClient.DownloadStringTaskAsync(uri);        Console.WriteLine(result);    }

  而之前的方式是这样的:

static void DownloadStringAsync(Uri uri)    {        var webClient = new WebClient();        webClient.DownloadStringCompleted += (s, e) =>            {                Console.WriteLine(e.Result);            };        webClient.DownloadStringAsync(uri);    }

也许前面这个例子不足以体现async和await带来的优越性,下面这个例子就明显多了:

public void CopyToAsyncTheHardWay(Stream source, Stream destination)    {        byte[] buffer = new byte[0x1000];        Action<IAsyncResult> readWriteLoop = null;        readWriteLoop = iar =>        {            for (bool isRead = (iar == null); ; isRead = !isRead)            {                switch (isRead)                {                    case true:                        iar = source.BeginRead(buffer, 0, buffer.Length,                            readResult =>                            {                                if (readResult.CompletedSynchronously) return;                                readWriteLoop(readResult);                            }, null);                        if (!iar.CompletedSynchronously) return;                        break;                    case false:                        int numRead = source.EndRead(iar);                        if (numRead == 0)                        {                            return;                        }                        iar = destination.BeginWrite(buffer, 0, numRead,                            writeResult =>                            {                                if (writeResult.CompletedSynchronously) return;                                destination.EndWrite(writeResult);                                readWriteLoop(null);                            }, null);                        if (!iar.CompletedSynchronously) return;                        destination.EndWrite(iar);                        break;                }            }        };        readWriteLoop(null);    }    public async Task CopyToAsync(Stream source, Stream destination)    {        byte[] buffer = new byte[0x1000];        int numRead;        while ((numRead = await source.ReadAsync(buffer, 0, buffer.Length)) != 0)        {            await destination.WriteAsync(buffer, 0, numRead);        }    }

可参看微软的官方网站:Visual Studio Asynchronous Programming,其官方文档Task-Based Asynchronous Pattern Overview介绍的非常详细, VisualStudio中自带的CSharp Language Specification中也有一些说明。

源自:http://blog.csdn.net/wulex/article/details/73499500

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台