在C#中同步包装异步方法

mik*_*imo 7 c# asynchronous synchronous wrapper

我有一个第三方库,其中包含一个异步执行函数的类.该类继承自Form.该功能基本上基于存储在数据库中的数据执行计算.完成后,它会在调用表单中调用_Complete事件.

我想要做的是同步调用该函数,但是从非Windows窗体应用程序.问题是,无论我做什么,我的应用程序块和_Complete事件处理程序永远不会触发.从Windows窗体我可以通过使用"完整"标志和"while(!complete)application.doevents"来模拟同步运行的函数,但显然application.doevents在非Windows窗体应用程序中不可用.

有什么东西阻止我在Windows窗体应用程序之外使用类的方法(由于它继承自'Form')?有什么方法可以解决这个问题吗?

谢谢,迈克

Kev*_*Kev 8

在尝试时,可能值得尝试类似下面的内容,使用WaitHandle来阻止当前线程而不是旋转并检查标志.

using System;
using System.Threading;

class Program
{
    AutoResetEvent _autoEvent;

    static void Main()
    {
        Program p = new Program();
        p.RunWidget();
    }

    public Program()
    {
        _autoEvent = new AutoResetEvent(false);
    }

    public void RunWidget()
    {
        ThirdParty widget = new ThirdParty();           
        widget.Completed += new EventHandler(this.Widget_Completed);
        widget.DoWork();

        // Waits for signal that work is done
        _autoEvent.WaitOne();
    }

    // Assumes that some kind of args are passed by the event
    public void Widget_Completed(object sender, EventArgs e)
    {
        _autoEvent.Set();
    }
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*ins 0

您有该组件的来源吗?听起来它依赖于从 WinForms 环境调用它的事实(这一定是库从 Form 继承的一个很好的理由!),但很难确定。