C# 从静态类调用委托
我有一个名为 Service 的静态类,它启动一个新线程来继续侦听来自其他进程的消息。在此类中,我管理一个在收到消息时需要调用的委托列表。这些委托的一些方法需要在主线程中运行。
例如,如果我以某种形式制造威胁,我可以这样做,
this.Invoke(@delegate, new object[] { messageReceived });
但我不能这样做,因为我在静态班级中。所以我尝试这样做:
@delegate.Invoke(messageReceived);
但它不起作用,因为它不会更改执行该方法的子进程(它是从我创建的威胁执行的,而不是从主威胁执行的)。
我该怎么办?
谢谢!
I've a static class called Service which starts a new thread to keep listening message from other process. In this class I manage a list of delegates which needs to be invoked when a message is received. Some of the methods of these delegates need to run in the main thread.
If I would create the threat in some form, for example, I could just do
this.Invoke(@delegate, new object[] { messageReceived });
But I can't do that because I'm in a static class. So I tried doing like this:
@delegate.Invoke(messageReceived);
But it doesn't work because it doesn't change the subprocess where the method is executed (it is executed from my created threat, not from the main one).
How can I do?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(4)
为什么不使用 System.Threading.SynchronizationContext 类?
如果您将来打算转向 WPF,那么学习这一点是很好的。
同步上下文是处理线程间消息的标准可移植方法。
每个系统都有一个版本...来自 System.Web、Windows 窗体、WPF 以及自定义同步上下文。
public static class MyClass
{
public static void MyFunction(MyObject messageReceived )
{
// Call this stuff from non-gui thread.
SynchronizationContext syncContext = SynchronizationContext.Current;
syncContext.Send(MyMethod, param);
// You can also use SyncContext.Post if you don't need to wait for completion.
syncContext.Post(MyMethod, param);
}
private static void MyMethod(object state)
{
MyObject myObject = state as MyObject;
... do my stuff into the gui thread.
}
// Using anonymous delegates you can also have a return value using Send.
public static int MyFunctionWithReturnValue(MyObject parameter)
{
int result = 0;
SynchronizationContext.Current.Post(delegate (object p)
{
result = parameter.DoSomething()
}, null);
return result;
}
}
抱歉,我在问题中忘记了。我还想避免在静态类中使用 System.Windows.Forms 类。
我发现的最简单的方法是从委托对象调用 Invoke 方法(正如我之前尝试过的那样,但它不起作用)。在委托的方法中执行以下操作:
if (this.InvokeRequired)
this.Invoke(MethodWhichDoesRealStuff, new object[] { message });
else
MethodWhichDoesRealStuff(message);
我还注意到我实际上不必管理类中的委托列表。一次活动对我来说正是如此。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
修改您的
static
类以接受参数。将您的
this
变量作为参数传递给您的static
类。Modify your
static
class to accept a parameter.Pass your
this
variable as a parameter to yourstatic
class.