简体   繁体   English

需要帮助来了解C#异步方法(HttpWebRequest)

[英]Need help understanding C# Async Methods (HttpWebRequest)

I don't really understand the flow/workings of async methods. 我不太了解异步方法的流程/工作原理。 I have created a WebRequest that posts data to the server. 我创建了一个将数据发布到服务器的WebRequest It contains alot more code than if I used normal methods. 它包含比我使用常规方法更多的代码。

I noticed in all callbacks, I get the request from result.AsyncState . 我注意到在所有回调中,我都是从result.AsyncState获取请求的。 Also say just to write to the request stream, I need to have 1 callback ( reqCB ) ... Its so confusing. 也要说只是写入请求流,我需要有1个回调( reqCB )...如此令人困惑。 I wonder how they map out to activities in real life? 我想知道他们如何映射到现实生活中的活动?

private void Button_Click(object sender, RoutedEventArgs e)
{
    var req = (HttpWebRequest)WebRequest.Create("http://localhost/php/upload.php");
    req.Method = "POST";
    req.ContentType = "application/x-www-form-urlencoded";

    req.BeginGetRequestStream(new AsyncCallback(ReqCB), req);
}

private void ReqCB(IAsyncResult result)
{
    var req = (HttpWebRequest)result.AsyncState;
    using (var reqStream = req.EndGetRequestStream(result)) {
        var writer = new StreamWriter(reqStream);
        writer.Write("foo=bar&baz=12");
        writer.Flush();
    }
    req.BeginGetResponse(new AsyncCallback(ResCB), req);
}

private void ResCB(IAsyncResult result)
{
    var req = (HttpWebRequest)result.AsyncState;

    var res = req.EndGetResponse(result);
    using (var resStream = res.GetResponseStream()) {
        var reader = new StreamReader(resStream);
        resStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(ReadCB), req);
        _dispatcher.Invoke(new Action(delegate
        {
            txt1.Text = res.ContentLength.ToString();
        }));
    }
}

It may help to think of a list which you've handed to someone. 考虑一下您交给某人的清单可能会有所帮助。 Each step takes lots of time, so they forget what the next step is before they're done. 每个步骤都需要花费大量时间,因此他们在完成之前会忘记下一步是什么。 So, they reach into their pocket, pull out the list, and realize what to do next. 因此,他们伸手去拿钱,拿出清单,意识到下一步该做什么。

The IAsyncResult has an general AsyncState property so it can be used by many different types of callback arrangements. IAsyncResult具有常规的AsyncState属性,因此可以被许多不同类型的回调安排使用。 This is why you need to cast the result. 这就是为什么您需要转换结果的原因。

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

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