简体   繁体   English

当看起来毫无意义时,为什么作者使用ContinueWith()和异步方法变体

[英]Why does the author use ContinueWith() and async methods variants when it seems pointless

I've been reading Essential C# 6.0 recently. 我最近一直在阅读Essential C#6.0。 In the chapter of the book where author explains multi threading he shows this method and I don't understand two things about it which don't seem to be explained anywhere. 在这本书的作者解释多线程的那一章中,他展示了这种方法,我不了解关于它的两件事,似乎在任何地方都没有解释。

private static Task WriteWebRequestSizeAsync(string url)
{
    StreamReader reader = null;
    WebRequest webRequest = WebRequest.Create(url);

    Task task = webRequest.GetResponseAsync()
        .ContinueWith(antecedent =>
        {
            WebResponse response = antecedent.Result;
            reader = new StreamReader(response.GetResponseStream());
            return reader.ReadToEndAsync();
        })
        .Unwrap()
        .ContinueWith(antecedent =>
        {
            if(reader != null) reader.Dispose();
            string text = antecedent.Result;
            Console.WriteLine(text.Length);
        });
    return task;
}

1. Why does the author use ContinueWith() methods and calls them essential ? 1.为什么作者使用ContinueWith()方法并将其称为必不可少的 How is his way of doing it better than my approach, which does not utilize these methods? 与未使用这些方法的方法相比,他的方法做得如何?

private static Task WriteWebRequestSizeAsync(string url)
{
    return Task.Run(() =>
    {
        WebRequest webRequest = WebRequest.Create(url);
        WebResponse response = webRequest.GetResponseAsync().Result;
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            string text = reader.ReadToEndAsync().Result;
            Console.WriteLine(text.Length);
        }
    });
}

2. Why does the author use async variants of the methods and then access their result via .Result property, instead of using not async variants as it appears to have the same result at the end. 2.为什么作者使用方法的异步变体,然后通过.Result属性访问其结果,而不是使用非异步变体,因为它看起来在最后具有相同的结果。 Please, notice that I haven't changed it in my approach above 请注意,我在上面的方法中没有更改它

Although you are calling GetResponseAsync() in your method, however, trying to use .Result makes it a blocking call.As a result of this your task continues to wait for the result to be available wasting cpu cycles. 虽然你在你的方法调用GetResponseAsync(),但是,试图使用.Result使它成为阻挡call.As这样的结果你的任务继续等待的结果是可用的浪费CPU周期。

WebResponse response = webRequest.GetResponseAsync().Result; //blocking call

However, in the example by author, GetResponseAsync() is followed by a ContinueWith(). 但是,在作者的示例中,GetResponseAsync()之后是ContinueWith()。 This means that Task on which GetResponseAsync() is called won't be blocked and can be utilized to do something else. 这意味着在其上调用GetResponseAsync()的Task不会被阻塞,并且可以用于执行其他操作。 When the result of GetResponseAsync() is available the continuation will run. 当GetResponseAsync()的结果可用时,将继续运行。

 webRequest.GetResponseAsync()
        .ContinueWith(antecedent =>
        {
            WebResponse response = antecedent.Result;
            reader = new StreamReader(response.GetResponseStream());
            return reader.ReadToEndAsync();
        })

Same example can also be written using async and await instead of continuation...This will have a similar effect of continuations . 也可以使用async和await而不是continuation来编写相同的示例...这将具有continuation的类似效果。 However, this will be more natural to read. 但是,阅读起来会更自然。

var result = await webRequest.GetResponseAsync();
//do something with result now.

似乎作者使用了堆叠的连续性,以便根据关注点分离原则拆分操作。

Main difference between yours and authors way is that author runs code in the same thread from what method WriteWebRequestSizeAsync while your code will run in some thread from ThreadPull. 与您的作者方式之间的主要区别在于,作者使用哪种方法在同一线程中运行WriteWebRequestSizeAsync方法中的代码,而您的代码将在ThreadPull中的某些线程中运行。 I don't know context so may be it's essential. 我不知道背景,所以可能是必不可少的。 About second question. 关于第二个问题。 If author calls not async methods he could not get tasks and attach to them ContinueWith . 如果作者调用了非异步方法,那么他将无法获取任务并将其附加到ContinueWith

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM