我想异步执行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
声明?
答案 0 :(得分:4)
如果您正在编写WinRT组件,则必须返回IAsyncOperation<TResult>
。但是,我建议将IAsyncOperation<TResult>
代码编写为更自然的async
/ await
实现的简单包装。
有一个专为此场景编写的extension method:
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;
}
答案 1 :(得分:2)
您可以使用 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;
}