我目前正在开发WCF发布订阅服务。我的服务有以下代码,
public void PublishPost(string postSampleData)
{
PostChangeEventArgs e = new PostChangeEventArgs();
e.PostData = postSampleData;
PostChangeEvent(this, e);
}
并且postChangeEvent的代码是
public class PostChangeEventArgs : EventArgs
{
public string PostData;
}
在我的客户端文件中,我在main方法中编写了这段代码,
class Program : IPostingContractCallback
{
static void Main()
{
InstanceContext site = new InstanceContext(null, new Program());
PostingContractClient client = new PostingContractClient(site);
WSDualHttpBinding binding = (WSDualHttpBinding)client.Endpoint.Binding;
String clientcallbackaddress = binding.ClientBaseAddress.AbsoluteUri;
clientcallbackaddress += Guid.NewGuid().ToString();
binding.ClientBaseAddress = new Uri(clientcallbackaddress);
client.Subscribe();
}
public void PostReceived(string postSampleData)
{
MessageBox.Show("PostChange(item {0})", postSampleData);
}
}
以及我的数据源代码......
class Program : IPostingContractCallback
{
static void Main(string[] args)
{
InstanceContext site = new InstanceContext(new Program());
PostingContractClient client = new PostingContractClient(site);
client.PublishPost("testing");
Console.WriteLine();
Console.WriteLine("Press ENTER to shut down data source");
Console.ReadLine();
//Closing the client gracefully closes the connection and cleans up resources
client.Close();
}
public void PostReceived(string postSampleData)
{
Console.WriteLine("PostChange(item {0})",postSampleData);
}
}
运行服务后,客户端,然后是数据源,我想从我的客户端收到一个弹出消息框。但是在行上出现错误
PostChangeEvent(this, e);
对象引用未设置为对象的实例。
任何人都知道如何解决这个问题?
答案 0 :(得分:2)
听起来没有订阅这个活动。要检查这一点,您应该使用:
var handler = PostChangeEvent;
if (handler != null)
{
handler(this, e);
}
这将停止NullReferenceException
,但当然它不会解决为什么没有订阅者......你没有展示订阅该事件的任何内容 - 你期望订阅什么?< / p>