如何返回 IAsyncOperation 结果

本文关键字:TReturn 结果 IAsyncOperation 何返回 返回 | 更新日期: 2023-09-27 18:36:19

我想异步执行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 ?????;
    }

我应该如何写上面的return语句?

如何返回 IAsyncOperation<TReturn> 结果

如果要编写 WinRT 组件,则必须返回IAsyncOperation<TResult>。但是,我建议编写IAsyncOperation<TResult>代码,就像围绕更自然的async/await实现的简单包装器一样。

有一个专门为此方案编写的扩展方法:

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;
}
您可以使用

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;
}