C# 如何返回IAsyncOperation<;TReturn>;结果如何?

C# 如何返回IAsyncOperation<;TReturn>;结果如何?,c#,asynchronous,C#,Asynchronous,我想异步执行CPU密集型工作。我想使用这样的代码: .... updateGUIObj = await setSelectedGUICellValueAsync(arg1, arg2, cssId, isInitializeCbxChecked); .... public IAsyncOperation<UpdateGUIObj> setSelectedGUICellValueAsync(int arg1, int arg2, String cssId,

我想异步执行CPU密集型工作。我想使用这样的代码:

   ....
   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 ?????;
    }
。。。。
updateGUIObj=await setSelectedGUICellValueAsync(arg1、arg2、cssId、isInitializeCbxChecked);
....
public IAsyncOperation setSelectedGUICellValueAsync(int arg1、int arg2、字符串cssId、bool isInitializeCbxChecked)
{
updateGUIObj=新的updateGUIObj();
..//计算密集型工作设置“updateGUIObj”
返回?????;
}

如何编写上面的
return
语句?

您可以使用async/await模式并返回
Task
对象:

...
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;
}
。。。
var updateGUIObj=await setSelectedGUICellValueAsync(arg1、arg2、cssId、isInitializeCbxChecked);
...
公共异步任务setSelectedGUICellValueAsync(int arg1、int arg2、字符串cssId、bool isInitializeCbxChecked)
{
var updateGUIObj=新的updateGUIObj();
//..计算密集型工作设置“updateGUIObj”
返回updateGUIObj;
}

如果您正在编写WinRT组件,则必须返回
IAsyncOperation
。但是,我建议编写
IAsyncOperation
代码,就像编写更自然的
async
/
wait
实现的简单包装一样

有一个专门为此场景编写的示例:

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;
}
public IAsyncOperation setSelectedGUICellValueAsync(int arg1、int arg2、字符串cssId、bool isInitializeCbxChecked)
{
返回SetSelectedGuiCellValueAsync(arg1、arg2、cssId、isInitializeCbxChecked)。AsAsAsyncOperation();
}
专用异步任务SetSelectedGuiCellValueAsync(int arg1、int arg2、字符串cssId、bool isInitializeCbxChecked)
{
updateGUIObj=新的updateGUIObj();
等待任务。运行(…);
返回updateGUIObj;
}

为什么不使用任务api?如果需要,Task.Run将在另一个线程中执行,并返回一个等待的任务。谢谢Stephen。从我最初的阅读来看,我认为我必须返回一个
IAsyncOperation
。有了您的评论,我重新阅读了它,现在很清楚,我只需要返回上述解决方案中建议的
任务