Wednesday, 2 May 2012

Using Task and WebRequest to asynchronously call RESTful service

Threading in C# is a good website describing Task Parallelism and other aspects of C# Threading.

[Test]
//For GET/POST/PUT/DELETE calls
public void TestWebRequest()
{
    Task<string> task = Task.Factory.StartNew<string>(() => // Begin task
    {
        var req = (HttpWebRequest)WebRequest.Create("http://localhost:52292/Api/Product/31a3653e-2db0-429e-8cfb-8842bd984b69");
        req.Method = "GET"; //POST/PUT/DELETE
        using (var response = (HttpWebResponse)req.GetResponse())
        {
            if (response.ContentLength > 0)
            {
                var reader = new StreamReader(response.GetResponseStream());
                return reader.ReadToEnd();
            }
        }
        return null;
    });
    Console.WriteLine("Do something else..");
    //wait for Task Result
    string result = task.Result;
    Console.WriteLine("Completed..");
    Console.WriteLine(result);
}
[Test]
//this is only for GET calls
public void TestWebClient()
{
    Task<string> task = Task.Factory.StartNew<string>(() => // Begin task
    {
        using (var wc = new WebClient())
            return
                wc.DownloadString("http://localhost:52292/Api/Product/31a3653e-2db0-429e-8cfb-8842bd984b69");
    });
    Console.WriteLine("Do something else..");
    //wait for Task Result
    string result = task.Result;
    Console.WriteLine("Completed..");
    Console.WriteLine(result);
}

No comments:

Post a Comment