等到偶发事件发生后再处理

时间:2018-09-25 18:40:18

标签: c# asynchronous events

我正在远程控制外接摄像机。我可以通过异步调用TakePhotoAsync()方法来拍照,并且在拍照并准备下载时,发生事件DownloadReady,其中包含有关拍照图片的DownloadInfo。我有方法Cam_DownloadReady(...)处理此事件。 这是由API提供的,我无法更改任何内容。

但是我需要同步拍照。类似于调用TakePhotoAsync()并在此行等待,直到事件DownloadReady发生为止,该事件调用Cam_DownloadReady(...)方法,并在执行并完成此方法后,然后// continue..(如代码部分)。这可能吗?谢谢

public Task<CameraImage> GetImageFromCameraAsync(string cameraId) 
{
    APIHandler = new CanonAPI();
    Camera MainCamera = APIHandler.GetCameraList()[0];
    MainCamera.DownloadReady += Cam_DownloadReady;
    MainCamera.OpenSession();
    MainCamera.TakePhotoAsync();
    // wait here until event occurs and is processed
    // Cam_DownloadReady(...) is called and finished
    // continue ...
}

private void Cam_DownloadReady(Camera sender, DownloadInfo Info)
{
    sender.DownloadFile(Info, saveImageDir); //save picture on PC
}

1 个答案:

答案 0 :(得分:0)

您可以使用ManualResetEvent来实现:

using System.Threading;     
public ManualResetEvent mre = new ManualResetEvent(false); // created in the unsignaled state.

    public Task<CameraImage> GetImageFromCameraAsync(string cameraId)
    {
        mre.Reset(); // Set the state of the event to be nonsignaled 
        APIHandler = new CanonAPI();
        Camera MainCamera = APIHandler.GetCameraList()[0];
        MainCamera.DownloadReady += Cam_DownloadReady;
        MainCamera.OpenSession();
        MainCamera.TakePhotoAsync();
        // wait here until event occurs and is processed
        mre.WaitOne(); // Block the current thread until the current wait handle receives a signal
        // Cam_DownloadReady(...) is called and finished
        // continue ...
    }

    private void Cam_DownloadReady(Camera sender, DownloadInfo Info)
    {
        sender.DownloadFile(Info, saveImageDir); //save picture on PC
        mre.Set(); // Set the state of the event to signaled, allowing mre.WaitOne() above to proceed.
    }
相关问题