我目前正在开发WCF发布订阅服务。订阅者是一个winform应用程序。由于订阅者需要为服务实现回调方法,在我的例子中是PostReceived()方法,并且发布者具有PublishPost()方法。
对于我的winform的PostReceived()方法,它无法访问我的winform的UI线程。 subscribe方法在我的main方法上完成。如何以能够访问标签和我的mainForm的方式对PostReceived()方法进行编程?
修改
我到目前为止尝试的是从program.cs调用mainForm对象,但是当我运行所有3时它崩溃,说明它无法访问UI线程的错误。
编辑2
我尝试使用以下代码,但是有错误。
mainForm b;
public void PostReceived(string postSampleData)
{
b.BeginInvoke((MethodInvoker)delegate()
{
b.lblSearch.Text = "lakjslkaja";
});
运行代码后,出现
错误Object reference not set to an instance of an object.
知道怎么解决吗?
答案 0 :(得分:4)
你的PostReceived方法应该是这样的
void PostReceived()
{
yourform.BeginInvoke((MethodInvoker)delegate()
{
yourform.button.Text = "new label";
//More stuff here
});
}
这将保证在UI线程中调用 BeginInvoke 之后的所有内容。