Search code examples
c#asynchronoustask-parallel-librarytaskresponse

Other ways to start a task in an asynchronous manner


What are some other ways to create a task to begin and get a response with the same concept of the code shown below: (Using .Net 4)

var uri = new Uri(website.SiteUrl);
var myReq = (HttpWebRequest)WebRequest.Create(uri);

var task = Task<WebResponse>.Factory.FromAsync(
                myReq.BeginGetResponse,
                myReq.EndGetResponse,
                null);

Solution

  • If you are using .Net 4.5

    var task = myReq.GetResponseAsync();
    

    For .Net 4.0 you can write something like this

    public Task<HttpWebResponse> GetAsync(HttpWebRequest req)
    {
        var tcs = new TaskCompletionSource<HttpWebResponse>();
        req.BeginGetResponse(e =>
            {
                if(e.IsCompleted)
                    tcs.TrySetResult((HttpWebResponse)req.EndGetResponse(e));
            }, null);
        return tcs.Task;
    }
    

    But I don't see anything better than your current code.