I don't really understand the flow/workings of async methods. I have created a WebRequest
that posts data to the server. It contains alot more code than if I used normal methods.
I noticed in all callbacks, I get the request from result.AsyncState
. Also say just to write to the request stream, I need to have 1 callback (reqCB
) ... Its so confusing. 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();
}));
}
}