I want to perform CPU intensive work asynchronously. I thought to use code like this one:
....
updateGUIObj = await setSelectedGUICellValueAsync(arg1, arg2, cssId, isInitializeCbxChecked);
....
public IAsyncOperation<UpdateGUIObj> setSelectedGUICellValueAsync(int arg1, int arg2, String cssId, bool isInitializeCbxChecked)
{
updateGUIObj = new UpdateGUIObj();
.... // compute intensive work setting "updateGUIObj"
return ?????;
}
How should I write the above return
statement?
If you use a Task return type for an async method, a calling method can use an await operator to suspend the caller's completion until the called async method has finished. In the following example, the WaitAndApologizeAsync method doesn't contain a return statement, so the method returns a Task object.
You should use the EndXXX of your async method to return the value. EndXXX should wait until there is a result using the IAsyncResult's WaitHandle and than return with the value.
DoSomething()' is an async method that returns 'Task', a return keyword must not be followed by an object expression.
Returning IAsyncOperation<TResult>
is necessary if you're writing a WinRT component. However, I recommend writing the IAsyncOperation<TResult>
code just as a simple wrapper around the more natural async
/await
implementation.
There's an extension method that was written specifically for this scenario:
public IAsyncOperation<UpdateGUIObj> setSelectedGUICellValueAsync(int arg1, int arg2, String cssId, bool isInitializeCbxChecked)
{
return SetSelectedGuiCellValueAsync(arg1, arg2, cssId, isInitializeCbxChecked).AsAsyncOperation();
}
private async Task<UpdateGUIObj> SetSelectedGuiCellValueAsync(int arg1, int arg2, String cssId, bool isInitializeCbxChecked)
{
updateGUIObj = new UpdateGUIObj();
await Task.Run(....);
return updateGUIObj;
}
You can use async/await pattern and returns Task<>
objects instead:
...
var updateGUIObj = await setSelectedGUICellValueAsync(arg1, arg2, cssId, isInitializeCbxChecked);
...
public async Task<UpdateGUIObj> setSelectedGUICellValueAsync(int arg1, int arg2, String cssId, bool isInitializeCbxChecked)
{
var updateGUIObj = new UpdateGUIObj();
// .... compute intensive work setting "updateGUIObj"
return updateGUIObj;
}
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