来自 美高梅4858官方网站 2019-10-19 10:26 的文章
当前位置: 美高梅4858官方网站 > 美高梅4858官方网站 > 正文

异步和等待

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);
        }
    }

恐怕后边这一个例子不足以呈现async和await带来的优越性,下边那些例子就旗帜明显多了:

 

源自:

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

 

可参考微软的官方网站:Visual Studio Asynchronous Programming,其官方文书档案Task-Based Asynchronous Pattern Overview介绍的十一分详尽, VisualStudio中自带的CSharp Language Specification中也会有一部分验证。

  而从前的议程是那般的:

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

   在.Net 4.5中,通过async和await三个首要字,引进了一种新的基于职分的异步编制程序模型(TAP)。在这里种方式下,能够因此类似同步方式编写异步代码,不小简化了异步编程模型。如下式一个轻易易行的实例:

本文由美高梅4858官方网站发布于美高梅4858官方网站,转载请注明出处:异步和等待

关键词: