【发布时间】:2011-05-03 16:04:54
【问题描述】:
大家好 我对所有这些多线程的东西有点陌生,所以如果我解释得不好,请原谅:)
假设我有两个类:
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,需要在主应用程序线程中执行的代码也不会在主应用程序线程中执行(我不这么认为) 我试过在代码中输出当前线程名,并没有输出主应用线程名。
有没有办法可以做到这一点? 如果我解释得很糟糕,请告诉我:) 谢谢!
【问题讨论】:
-
请解释为什么您需要在主(或其他)线程上执行该代码。您使用
InvokeMember的方法是完全错误的,如果不澄清您的意图,您就不能指望一个与您的实际情况相匹配的真正有用的答案。 -
请指定 WinForms 或 WPF
-
抱歉信息不足。这不是 WinForms 或 WPF,它是一个控制台应用程序。它需要在主线程上执行的原因有很多,其中一个是因为我正在构建一个使用 Lidgren 网络库的应用程序,并且我只能在库正在侦听的线程上发送网络消息。
标签: c# .net multithreading invoke