仅在调用外部事件处理程序时返回方法

时间:2015-11-24 08:58:19

标签: c# asynchronous

所以我想只在一些asnyc进程(但没有await)被finshed时返回一个方法。阻止事件处理程序的方法过程和waitint的最佳方法是什么。是的我可以做一个while循环来阻塞方法并等待一个布尔值,当调用事件处理程序时它将被切换。但我认为这不是最好的方法吗?

3 个答案:

答案 0 :(得分:2)

也许您正在寻找ManualResetEventSlim

public class ManualResetEventPlayground
{
    public ManualResetEventPlayground()
    {
        SomeEvent += (sender, e) =>
        {
            // Opens the door, blocked code will resume
            Console.WriteLine("Opening the door to let the method return...");
            _resetEvent.Set();
        };

        Task.Run(() => MethodThatMustWaitUntilSomeEventIsFired());
        Task.Run(() => MethodThatFiresTheEvent());
    }

    private event EventHandler SomeEvent;
    private static readonly ManualResetEventSlim _resetEvent = new ManualResetEventSlim(false);


    public string MethodThatMustWaitUntilSomeEventIsFired()
    {
        // Some stuff to do before blocking

        try
        {
            // This will block this thread until
            // the event is fired and opens the door
            Console.WriteLine("Blocking the thread calling the method");
            _resetEvent.Wait();
        }
        finally
        {
            _resetEvent.Reset();
        }

        Console.WriteLine("Now this method can be returned!");

        return "finished";
    }
    public void MethodThatFiresTheEvent()
    {
        Console.WriteLine("Firing the event...");

        if (SomeEvent != null) SomeEvent(this, new EventArgs());
    }
}

如果您在控制台应用程序上实例化此类,您将获得以下输出:

enter image description here

答案 1 :(得分:1)

async Task方法会返回Task<Result>个对象,您只需拨打task.Wait();

var task = new System.Net.WebClient().DownloadStringTaskAsync("http://google.com");
task.Wait();

Console.WriteLine(task.Result);

答案 2 :(得分:0)

如果您真的不想使用async / await,那么Monitor就是您的选择。

在主线程中:

// To wait for a signal from another thread
Monitor.Wait(SyncRoot);

在工作线程中:

Monitor.Pulse(SyncRoot);

SyncRoot是任何对象。