如何在.NET中的父线程上调用函数? [英] How to invoke a function on parent thread in .NET?

查看:54
本文介绍了如何在.NET中的父线程上调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.NET类库,其中包含一个类,该类具有执行一些冗长的操作的方法.客户端调用此方法时,应在新线程上执行冗长的操作,以避免阻塞调用方.但是一旦方法完成,它应该在主线程上执行一些代码.在WinForms应用程序中,我可以使用System.Windows.Forms.Control.Invoke方法,但这不是我的情况.那么如何在C#中实现呢?

I have a .NET class library containing a class with a method that performs some lengthy operation. When a client calls this method it should perform the lengthy operation on a new thread in order to avoid blocking the caller. But once the method finishes it should execute some code on the main thread. In a WinForms application I could have used the System.Windows.Forms.Control.Invoke method but this is not my case. So how can I achieve this in C#?

推荐答案

我找到了解决该问题的简单方法:

I found a simple solution to the problem :

我的COM对象的声明如下:

My COM object is declared like this:

public class Runner
{
    public void Run(string executable, object processExitHandler)
    {
        ThreadPool.QueueUserWorkItem(state =>
        {
            var p = new Process()
            {
                StartInfo = new ProcessStartInfo()
                {
                    FileName = executable
                }
            };
            p.Start();
            while (!p.HasExited)
            {
                Thread.Sleep(100);
            }

            state
                .GetType()
                .InvokeMember(
                    "call", 
                    BindingFlags.InvokeMethod, 
                    null, 
                    state, 
                    new object[] { null, p.ExitCode }
                );
        }, processExitHandler);
    }
}

在我的HTML页面中,我像这样使用它:

And in my HTML page I use it like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head><title>ActiveXRunner</title>    
    <script type="text/javascript">
    function runNotepad() {
        var ax = new ActiveXObject('ActiveXRunner.Runner');
        ax.Run('c:\\windows\\notepad.exe', h);
    }

    function h(exitCode) {
        alert('exitCode = ' + exitCode);
    }
    </script>
</head>
<body>
    <a href="#" onclick="runNotepad();">Run notepad and show exit code when finished</a>
</body>
</html>

这篇关于如何在.NET中的父线程上调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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