在C#包装同步异步方法

在C#包装同步异步方法

本文介绍了在C#包装同步异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有含有异步执行函数的类第三方库。该类从Form继承。基于存储在数据库中的数据的功能基本上执行计算。一旦完成,它调用调用形式_Complete事件。

I have a third party library containing a class which performs a function asynchronously. The class inherits from the Form. The function basically performs a calculation based on data stored in a database. Once it has finished, it calls a _Complete event in the calling form.

我想要做的就是调用函数同步,但是从非Windows窗体应用程序。问题是,无论我做什么,我的应用程序块和_Complete事件处理程序永远不会触发。从Windows窗体我可以模拟使用完整的标志同步运行功能和,而(!完成)a​​pplication.doevents,但显然application.doevents可用的心不是在非Windows窗体应用程序。

What I would like to do is call the function synchronously but from a non-windows form application. The problem is, no matter what I do, my application blocks and the _Complete event handler never fires. From a windows form I can simulate the function running synchronously by using a "complete" flag and a "while (!complete) application.doevents", but obviously application.doevents isnt available in a non-windows form application.

有一些会使用类的方法阻止我一个Windows窗体应用程序之外(由于它从形式继承)?
有没有一些方法,我可以解决此问题?

Is there something that would stop me using the class's method outside of a windows form application (due to it inheriting from 'Form') ?Is there some way I can work around this ?

谢谢,
迈克

推荐答案

目前它可能是值得尝试像它使用的WaitHandle来阻止当前线程,而不是旋转和检查标志下刺。

At a stab it might be worth trying something like the following which uses a WaitHandle to block the current thread rather than spinning and checking a flag.

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();
    }
}

这篇关于在C#包装同步异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:53