Calling async method synchronously
You can access the Result
property of the task, which will cause your thread to block until the result is available:
string code = GenerateCodeAsync().Result;
Note: In some cases, this might lead to a deadlock: Your call to Result
blocks the main thread, thereby preventing the remainder of the async code to execute. You have the following options to make sure that this doesn't happen:
explicitly execute your async method in a thread pool thread and wait for it to finish:
string code = Task.Run(() => GenerateCodeAsync).Result;
This does not mean that you should just mindlessly add .ConfigureAwait(false)
after all your async calls! For a detailed analysis on why and when you should use .ConfigureAwait(false)
, see the following blog post:
You should get the awaiter (GetAwaiter()
) and end the wait for the completion of the asynchronous task (GetResult()
).
string code = GenerateCodeAsync().GetAwaiter().GetResult();
You should be able to get this done using delegates, lambda expression
private void button2_Click(object sender, EventArgs e) { label1.Text = "waiting...."; Task<string> sCode = Task.Run(async () => { string msg =await GenerateCodeAsync(); return msg; }); label1.Text += sCode.Result; } private Task<string> GenerateCodeAsync() { return Task.Run<string>(() => GenerateCode()); } private string GenerateCode() { Thread.Sleep(2000); return "I m back" ; }