到目前为止,我可以创建一个委托类型,例如:
// Can't use Task in WinRT interface and TypedEventHandler doesn't work with async await
public delegate IAsyncOperation<string> AsyncEventHandler(object sender, object args);
然后像这样在 WinRT 对象中公开:
public AsyncEventHandler OnMyEvent { get; set; }
在 WinRT 对象中,我会这样称呼它:
if (OnMyEvent != null)
{
var result = await OnMyEvent.Invoke(this, someArgs);
// Do something with the result...
}
使用 WinRT 对象的客户端代码可以执行以下操作:
instanceOfWinRTObject.OnMyEvent = OnCalledBackFromWinRT;
但是因为委托返回 anIAsyncOperation
我们需要做一些包装:
private async Task<string> OnCalledBackFromWinRTAsync(object sender,
object args)
{
return await GetSomeStringAsync(args);
}
private IAsyncOperation<string> OnCalledBackFromWinRT(object sender, object args)
{
return OnCalledBackFromWinRTAsync(sender, args).AsAsyncOperation();
}
只是感觉必须有一种更清洁的方法来实现这一目标。