How to create an async method in C# 4 according to the best practices?

后端 未结 2 1137
清歌不尽
清歌不尽 2020-12-28 19:12

Consider the following code snippet:

public static Task FetchAsync()
{
    string url = \"http://www.example.com\", message = \"Hello World!\";         


        
相关标签:
2条回答
  • 2020-12-28 19:39

    You're correct in thinking that the Waits are unnecessary - Result will block until a result is ready.


    However, an even easier way would be to base it off use the examples provided in the ParallelExtensionsExtras library.

    They have made extensions for WebClient which do exactly what you're looking for:

    static Task<string> FetchAsync()
    {
        string url = "http://www.example.com", message = "Hello World!";
    
        return new WebClient().UploadStringTask(url, "POST", message);
    }
    

    You can read more about it in this post on the Parallel Programming with .NET blog.

    0 讨论(0)
  • 2020-12-28 19:54

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

    ..though, you may get it look more attractive by creating extension methods on WebRequest, Stream classes and cleanup the main method.

    P.S.: I hope C# 5.0 with it's new async keyword and library will be released soon.

    Reference: http://msdn.microsoft.com/en-us/vstudio/async.aspx

    0 讨论(0)
提交回复
热议问题