将事件处理程序与单例c#一起使用。EventHandler为null
我有一个单例类和一个eventHandler sendResponse。 我想在发布服务器引发订阅服务器时在订阅服务器类中执行一些操作 这件事将事件处理程序与单例c#一起使用。EventHandler为null,c#,delegates,singleton,C#,Delegates,Singleton,我有一个单例类和一个eventHandler sendResponse。 我想在发布服务器引发订阅服务器时在订阅服务器类中执行一些操作 这件事 public class Publisher { private static Publisher instance; public event EventHandler SendResponse; public static Publisher Instance { get {
public class Publisher
{
private static Publisher instance;
public event EventHandler SendResponse;
public static Publisher Instance
{
get
{
if (instance == null)
instance = new Publisher();
return instance;
}
}
public void Send()
{
this.SendResponse(instance, EventArgs.Empty);
}
}
在订户里,我说
public string performSomething()
{
Publisher copy = Publisher.Instance;
copy.SendResponse += new EventHandler(copy_SendResponse);
bool isCompleted = false;
// Start an async task method which is in another class and is the publisher.
while(isCompleted != true);
return "Success";
}
//Define the function copy_SendResponse.
public void copy_SendResponse()
{
isCompleted = true;
}
首先执行带有订阅服务器的代码。
但是,当我在发布服务器中调用Send()方法时,SendResponse没有绑定到任何东西。
在我使用的出版商中
// when async task completes
Publisher copy = Publisher.Instance;
copy.Send();
// end of function
在调试时,当我说copy.Send()时,SendResponse实际上是空的。
它抛出了一个错误“对象引用未设置为对象的实例。”首先,我会像这样删除singleton:
私有静态发布者实例=新发布者()代码>,在我看来,这比getter更清楚。第二,始终证明您的活动是否已订阅:
private void Send()
{
if (this.SendResponse != null)
{
this.SendResponse(this, EventArgs.Empty); // <<-- pass this
}
}
如果是私人的,你怎么能调用Send()
?是的,对不起。进行了更改在我的代码中是公开的那么有什么问题?什么是copy\u SendResponse,它被调用了吗?我调用copy.Send,我想让它实际调用copy\u sendResponseThanks来进行输入。我实际上正在编写一个API,它是订阅者。它生成一个asynctask并启动一个计时器并持续监视一个标志。在异步任务类中,当它完成时,我发送事件。copy_SendResponse()用于将标志设置为true。当标志为true时,我将API的响应作为成功返回。但问题是,在异步任务中,当我说copy.Send()时,它不会调用该方法。它抛出了一个错误。{“对象引用未设置为对象的实例。”}我认为您的体系结构有问题,不应该这样工作。我会在下班后搜索其他示例。
public class Publisher
{
// Instance
private static readonly Publisher instance = new Publisher();
public event EventHandler SendResponse;
public static Publisher Instance
{
get
{
return instance;
}
}
/// <summary>
/// Private constructor
/// </summary>
private Publisher()
{
}
public void Send()
{
// proof if subscipted
if (this.SendResponse != null)
{
// Pass this
this.SendResponse(this, EventArgs.Empty);
}
}
}
class Program
{
static void Main(string[] args)
{
var copy = Publisher.Instance;
copy.SendResponse += Copy_SendResponse;
var copy2 = Publisher.Instance;
copy2.Send();
Console.ReadLine();
}
/// <summary>
/// Event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void Copy_SendResponse(object sender, EventArgs e)
{
Console.WriteLine("It works!");
}
}