Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return IAsyncOperation<TReturn> result?

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?

like image 728
ema3272 Avatar asked Feb 26 '16 16:02

ema3272


People also ask

How to return Task in async method?

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.

How to return from async method c#?

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.

Is an async method that returns task a return keyword?

DoSomething()' is an async method that returns 'Task', a return keyword must not be followed by an object expression.


2 Answers

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;
}
like image 93
Stephen Cleary Avatar answered Sep 26 '22 10:09

Stephen Cleary


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;
}
like image 38
Arturo Menchaca Avatar answered Sep 27 '22 10:09

Arturo Menchaca