繁体   English   中英

在特定线程中执行方法/设置属性

[英]Execute a method/set property in a specific thread

大家好,我对所有这些多线程的东西有点陌生,所以如果我解释得不好,请原谅:)

假设我有两个课程:

class abc {
    public string SomeProperty {
        get { return something; }
        set { /* This code has to execute in the main application thread */ }
    }

    public void SomeMethod() {
        /* This code also has to execute in the main application thread */
    }
}

class def {
    abc obj;

    public def() {
        abc = new obj();
    }

    public void SomeMethod() {
        abc.SomeProperty = "SomeValue";
        abc.SomeMethod();
    }
}

我遇到的问题是让 SomeProperty 和 SomeMethod 在主应用程序线程上执行。 我努力了:

abc.GetType().InvokeMember("SomeProperty", System.Reflection.BindingFlags.SetProperty, null, abc, new object[] { "SomeValue" });
abc.GetType().InvokeMember("SomeMethod", System.Reflection.BindingFlags.InvokeMethod, null, abc, null);

但是,需要在主应用程序线程中执行的代码没有在主应用程序线程中执行,即使使用 InvokeMember (我不这么认为)我已经尝试在代码中输出当前线程名称,它output 不是主应用程序线程名称。

有没有办法我可以做到这一点? 如果我解释得很糟糕,请告诉我:)谢谢!

有多种方法可以做到这一点,但我的首选方法如下:

   protected void setTransactionButton(Boolean enabled)
    {
        (new Task(() =>
        {
            transcriptQuitButton.Enabled = enabled;
        })).Start(uiScheduler);
    }

在我的初始化代码中,我称之为:

uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

这样做是为了让事件在 UI 线程上发生并摆脱对BeginInvoke的需求。

您可以在很多地方找到BeginInvoke ,但如果您可以使用匿名函数,那么这里有一篇文章:

http://visualstudiomagazine.com/articles/2009/02/01/use-lambda-expressions-for-abstract-delegates.aspx

InvokeMember只是一种使用反射执行成员的方法。 它与线程无关。

我怀疑您真的在寻找Control.InvokeDispatcher.Invoke (或非阻塞BeginInvoke等价物)。

当然,您需要对适当的控件或调度程序的引用,然后创建适当的委托以在另一个线程上执行。 如果您寻找有关 Windows Forms 多线程(或 WPF)的教程,您应该会找到很多示例。 (我的网络连接目前很垃圾,否则我会为你找到一个像样的。)

编辑:既然您已经明确它是一个控制台应用程序,您将不得不制定某种形式的消息泵。 除非线程以某种方式监听消息,否则无法强制它执行另一段代码。 我没有使用过你谈到的库——但如果它迫使你在特定线程上执行代码,那么它应该提供一些等价的Control.Invoke等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM