打开异步调用变成同步 [英] Turn asynchronous calls into synchronous

查看:225
本文介绍了打开异步调用变成同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问有什么好的做法(模式)的转异步调用变成同步?
我有一个第三方库是谁的方法都是asynchronos,以获得almoust任何方法,你一定要听的一个事件,这会带来一定的范围内与它的结果。 基本上它看起来像:

Is there any good practice (pattern) in turning asynchronous calls into synchronous?
I have a third party library who's methods are all asynchronos, to get result of almoust any method you must listen to an event, which will bring some context with it. basically it looks like:

service.BeginSomething(...);
service.OnBeginSomethingCompleted += ;

我需要的是BeginSomething后执行一些code当它实际上是完整的(OnBeginSomethingCompleted被触发从而后)。这是非常inconvinient处理事件的响应。

what I need is to execute some code after BeginSomething when it is really complete (thus after OnBeginSomethingCompleted is triggered). It is very inconvinient to handle the response in the event.

我能想到的唯一的办法就是运行了Thread.Sleep循环,等到表单上的一些字段更新,但它看起来并不像很优雅sollution。

The only way I could think of is running a Thread.Sleep loop and wait till some field on the form is updated, but it doesn't look like very elegant sollution.

我使用的是.NET 4.0。

I'm using .net 4.0.

推荐答案

您可以继承主类,并提供了操作的同步版本。如果子类是不是一种选择,你可以创建一个扩展方法。这是怎么会事看起来。

You could subclass the main class and provide a synchronous version of the operation. If subclassing is not an option you could create an extension method. Here is how things might look.

public class Subclass : BaseClass
{
  public void Something()
  {
    using (var complete = new ManualResetEventSlim(false))
    {
      EventHandler handler = (sender, args) => { complete.Set(); };
      base.OnBeginSomethingCompleted += handler;
      try
      {
        base.BeginSomething();
        complete.Wait();
      }
      finally
      {
        base.OnBeginSomethingCompleted -= handler;
      }
    }
  }
}

更新:

有一件事我应该指出的是,这可能是有问题的一些情况。考虑这个例子。

One thing I should have pointed out is that this could be problematic in some cases. Consider this example.

var x = new Subclass();
x.BeginSomething();
x.Something();

这应该是显而易见的,在处理 的东西可以收到 OnBeginSomethingCompleted 事件从previous调用 BeginSomething 。请确保您防范这种莫名其妙。

It should be obvious that the handler in Something could receive the OnBeginSomethingCompleted event from the previous call to BeginSomething. Make sure you guard against this somehow.

这篇关于打开异步调用变成同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆