Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 单一事件的模式或语言工具?_C#_.net_Events_Design Patterns - Fatal编程技术网

C# 单一事件的模式或语言工具?

C# 单一事件的模式或语言工具?,c#,.net,events,design-patterns,C#,.net,Events,Design Patterns,我发现自己经常需要以下代码场景 订阅活动->等待活动->取消订阅活动 有没有比以下更好的方法: myEvent += mydelegate; while (mydelegatewasn't called) { // do stuff } myEvent -= mydelegate; 还有什么最好的方法来等待我的委托人完成它的工作? 而不是在while循环中旋转,你可能想考虑看看类来等待你的委托来完成它的工作。这样可以避免在等待代理完成时旋转 void Main() {

我发现自己经常需要以下代码场景

订阅活动->等待活动->取消订阅活动

有没有比以下更好的方法:

myEvent += mydelegate;
while (mydelegatewasn't called)
{
     // do stuff
}   
myEvent -= mydelegate;

还有什么最好的方法来等待我的委托人完成它的工作?

而不是在while循环中旋转,你可能想考虑看看类来等待你的委托来完成它的工作。这样可以避免在等待代理完成时旋转

void Main()
{
    RunActionOnceOnEvent(delegate()
    {
        // do stuff
    });
}

void RunActionOnceOnEvent(Action action)
{
    AutoResetEvent autoResetEvent = new AutoResetEvent(false);
    EventDelegate handler = delegate() 
    { 
        autoResetEvent.Set(); 
    }); 

    myEvent += handler;

    try
    {
        autoResetEvent.WaitOne();
        action();
    }
    finally 
    {
        myEvent -= handler;
    }
}

在减少不同事件的样板代码量方面,我不确定您能做多少,因为事件不是一流的。

如果AutoResetEvent是在线程本地作用域上创建的。可以为不同的线程创建AutoResetEvent的新实例。在两个线程同时触发事件的情况下,操作将执行两次。