如何为IAsyncOperation指定一个回调方法

How to specify a callback method for IAsyncOperation

本文关键字:一个 回调 方法 IAsyncOperation      更新时间:2023-10-16

是否可以指定在完成async操作后调用的方法?

平台:c++, Windows Phone 8

我需要实现异步发送UDP数据包的非阻塞方法。它们有我的方法:

onWriteComplete(int errorCode)

在操作完成时被回调。

这是我尝试过的:

res = await asyncWrite();
onWriteComplete( res );

异步操作在Windows Phone 8和Windows RT应用程序的所有语言中都以类似的方式工作。异步操作返回一个IAsyncOperation结果,你可以用它来链接一个函数,让它在操作完成后运行。

在c++中,你可以用类似c#的create_task和task::then函数来创建任务并链接它们。查看c++中异步编程(Windows Store Apps)的示例。

示例从IAsyncOperation结果创建一个任务,并安排另一个任务在第一个任务完成时执行:

auto deviceEnumTask = create_task(deviceOp);
// Call the task’s .then member function, and provide
// the lambda to be invoked when the async operation completes.
deviceEnumTask.then( [this] (DeviceInformationCollection^ devices ) 
{       
    for(int i = 0; i < devices->Size; i++)
    {
        DeviceInformation^ di = devices->GetAt(i);
        // Do something with di...          
    }       
}); // end lambda