In a windows 8 application in C#/XAML, I sometimes want to call an awaitable method from a non asynchronous method.
Actually is it correct to replace this :
public async Task<string> MyCallingMethod() { string result = await myMethodAsync(); return result; }
by this :
public string MyCallingMethod() { Task.Run(async () => { string result = await myMethodAsync(); return result; }); }
The advantage for me is that I can use MyCallingMethod without await but is this correct? This can be an advantage if I want to pass a ref parameter for MyCallingMethod since It is not possible to have ref parameters in an async method.
The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.
You can use the await keyword on its own (outside of an async function) within a JavaScript module. This means modules, with child modules that use await , wait for the child module to execute before they themselves run, all while not blocking other child modules from loading.
There's no rule that says that "asynchronous cannot call asynchronous". There are specific rules in place, such as "future cannot call future". A Queueable can call another Queueable, a Batchable can call another Batchable in the finish method, and Scheduleable methods can call Batchable and Queueable methods.
To control the spread, you might think to yourself that all you need to do is run your async functions synchronously. But this is a trap. It turns out there really is no reliable way to run an asynchronous method synchronously.
In non-async method you can either start the Task asynchronously and not wait for the result:
public void MyCallingMethod() { Task t = myMethodAsync(); }
or you can attach ContinueWith event handler, which is called after finishing the Task,
public void MyCallingMethod() { myMethodAsync().ContinueWith( result => { // do stuff with the result }); }
or you can get the result from the Task synchronously:
public string MyCallingMethod() { string result = myMethodAsync().Result; return result; }
You really shouldn't try to do something like that if you're on the UI thread, because that will mean you will block the thread. You should instead work around the ref
parameter, for example by accepting a parameter of a simple class type, that contains the value you want to change.
Another reason why not to do this is that it still won't let you use ref
parameters, because lambdas can't access ref
parameters of the enclosing method.
But if you really want to do this (again, I really think you shouldn't), then you will need to get the result of the Task
. Something like:
public string MyCallingMethod() { var task = Task.Run(async () => { return await myMethodAsync(); }); return task.Result; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With