java 等待事件_等待异步方法,其中完成由事件处理程序发出信号

我正在使用Windows Phone 8中的Contacts对象,在异步方法中调用SearchAysnc . SearchAsync要求处理程序订阅SearchCompleted事件,并通过事件参数之一传递其结果,async方法需要执行其工作(包括调用其他异步方法) .

你如何等待事件的异步完成,即事件模式和异步/等待模式之间的桥接?

我能提出的唯一解决方案是使用EventWaitHandle,在等待的任务中等待它,如下所示:

using System.Threading;

async Task MyMethod()

{

string result = null;

Contacts cons = new Contacts();

EventWaitHandle handle = new EventWaitHandle(false,EventResetMode.ManualReset);

cons.SearchCompleted += (sender,args) =>

{

// I do all my work on the results of the contact search in this handler

result = SomeOtherSynchronousOperation(args.Results);

// When I'm done, I release the thread which was waiting for the results

handle.Set();

};

cons.SearchAsync(String.Empty, FilterKind.None, "My Contact");

// I can't block this thread (or can I?)

// So, I launch a task whose sole job is to wait

await Task.Run(()=>

{

// This gets released by the Contacts.SearchCompleted handler when its work is finished,

// so that MyMethod can finish up and deliver its result

handle.WaitOne();

}

await DoOtherStuffWithResult(result);

return result;

}

我的实际解决方案(不完全如上所示)确实有效 . 虽然上面的代码并不能准确地表示已实现的解决方案(可能是一个或两个编译问题),但它应该用于表达概念并说明我的问题 .

它让我想知道这是否是唯一的方法,或者是接近最佳实践方式的任何地方等待事件处理程序的执行,如果没有,那么在这里需要做什么是“最佳实践” .

Windows同步原语是否仍然在async / await世界中占有一席之地?

(根据提供的答案)

这是正确的吗?

using Microsoft.Phone.UserData;

string ExtractWhatIWantFromResults(IEnumerable results)

{

string result;

// Do my processing on the list of contacts, stuff the results into result

return string;

}

async Task MyMethod()

{

Contacts cons = new Contacts();

TaskCompletionSource tcs = new TaskCompletionSource();

cons.SearchCompleted += (sender,args) =>

{

tcs.TrySetResult(ExtractWhatIWantFromResults(args.Results));

};

cons.SearchAsync(String.Empty, FilterKind.None, "My Contact");

return tcs.Task;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值