如何根据最佳实践在C#4中创建异步方法? [英] How to create an async method in C# 4 according to the best practices?
问题描述
请考虑以下代码段:
public static Task<string> FetchAsync()
{
string url = "http://www.example.com", message = "Hello World!";
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Post;
return Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null)
.ContinueWith(t =>
{
var stream = t.Result;
var data = Encoding.ASCII.GetBytes(message);
Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, data, 0, data.Length, null, TaskCreationOptions.AttachedToParent)
.ContinueWith(t2 => { stream.Close(); });
})
.ContinueWith<string>(t =>
{
var t1 =
Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null)
.ContinueWith<string>(t2 =>
{
var response = (HttpWebResponse)t2.Result;
var stream = response.GetResponseStream();
var buffer = new byte[response.ContentLength > 0 ? response.ContentLength : 0x100000];
var t3 = Task<int>.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent)
.ContinueWith<string>(t4 =>
{
stream.Close();
response.Close();
if (t4.Result < buffer.Length)
{
Array.Resize(ref buffer, t4.Result);
}
return Encoding.ASCII.GetString(buffer);
});
t3.Wait();
return t3.Result;
});
t1.Wait();
return t1.Result;
});
}
它应该返回Task<string>
,发送带有一些数据的HTTP POST请求,以字符串形式从Web服务器返回结果,并应尽可能高效.
It should return Task<string>
, send HTTP POST request with some data, return a result from webserver in a form of string and be as much efficient as possible.
- 在上面的示例中,您发现与异步流有关的任何问题吗?
- 在此示例中,可以将.Wait()包含在.ContinueWith()中
- 在这种和平的代码形式下(您暂时保留异常处理),您还看到其他任何问题吗?
推荐答案
如果与异步相关的C#4.0代码庞大而丑陋-可能会正确实施该代码.如果它又好又短,那么很可能不是;)
If async related C# 4.0 code is huge and ugly - there is a chance that it's implemented properly. If it's nice and short, then most likely it's not ;)
..尽管如此,通过在WebRequest上创建扩展方法,Stream类并清除main方法,您可能会使其看起来更具吸引力.
..though, you may get it look more attractive by creating extension methods on WebRequest, Stream classes and cleanup the main method.
PS :我希望C#5.0带有新的async
关键字和库即将发布.
P.S.: I hope C# 5.0 with it's new async
keyword and library will be released soon.
参考: http://msdn.microsoft .com/en-us/vstudio/async.aspx
这篇关于如何根据最佳实践在C#4中创建异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!