Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awaiting a non-async method

I'm thoroughly confused by the whole await / async pattern in C#.

I have a forms app, and I want to call a method that takes 20 seconds to do a ton of processing. Therefore I want to await it. I thought the correct way was to mark it as async Task but doing this produces a warning because I don't use await anywhere within it.

A google revealed something about returning a TaskCompletionSource<T> but I don't have a return type, since it's void.

How can I call this method using await?

like image 337
NibblyPig Avatar asked Sep 16 '13 14:09

NibblyPig


People also ask

What happens if you await a non async function?

This rule applies when the await operator is used on a non-Promise value. await operator pauses the execution of the current async function until the operand Promise is resolved. When the Promise is resolved, the execution is resumed and the resolved value is used as the result of the await .

Can I await a non async method?

You can not use the await keyword in a regular, non-async function. JavaScript engine will throw a syntax error if you try doing so.

Can use await for a non async function in JS?

They can't, because: JavaScript works on the basis of a "job queue" processed by a thread, where jobs have run-to-completion semantics, and. JavaScript doesn't really have asynchronous functions — even async functions are, under the covers, synchronous functions that return promises (details below)


1 Answers

Call your method as following:

await Task.Run(() => YourMethod()); 

When you use the Task.Run method it creates an awaitable task for you.

like image 136
SynerCoder Avatar answered Oct 23 '22 20:10

SynerCoder