C# - Is Task.Result blocking?

Yes Accessing Task.Result is the same as calling Task.Wait().
The MSDN documentation states:
public TResult Result { get; }

Accessing the property's get accessor blocks the calling thread until the asynchronous operation is complete; it is equivalent to calling the Wait method.

In the example below, the HttpGetAsync method will run asynchronously, until task.Result is accessed, at which point execution will block until the HTTP request completes.

using System;
using System.Net.Http;
using System.Threading.Tasks;
 
namespace Zuga.net
{
    class Program
    {
        static void Main(string[] args)
        {
            var task = HttpGetAsync("http://zuga.net/");
 
            string html = task.Result;
 
            Console.WriteLine("HTML = " + html);
        }
 
        public async static Task<string> HttpGetAsync(string uri)
        {
            string content = null;
 
            var client = new HttpClient();
            var response = await client.GetAsync(uri);
            if (response.IsSuccessStatusCode)
            {
                content = await response.Content.ReadAsStringAsync();
            }
 
            return content;
        }
    }
}

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath