繁体   English   中英

如何安全地确保 C# 中的异步方法完成?

[英]How to safely make sure an async method in C# is completed?

请原谅这个可能愚蠢的问题。 两个代码片段之间有区别吗?

示例 1:在同步方法中运行异步方法 CapturePhotoToStorageFileAsync

class Core
{
    async void ProcessCommand(Command cmd)
    {
        // Do some stuff
        await JobManager.ReportTrigger(cmd.TriggerID);
        SendCommand(Command reply);
    }
}

class JobManager
{
    async Task ReportTrigger(Int32 triggerID)
    {
        await Task.Delay(300);
        Webcam.CapturePhotoToFile();
        await Task.Delay(100);
    }
}

class WebCam
{
    void CapturePhotoFile()
    {
        m_MediaCapture.CapturePhotoToStorageFileAsync( ImageEncodingProperties.CreateJpeg(), file );
    }
}

示例 2:将异步方法 CapturePhotoToStorageFileAsync 作为任务运行:

class Core
{
    async void ProcessCommand(Command cmd)
    {
        // Do some stuff
        await JobManager.ReportTrigger(cmd.TriggerID);
        SendCommand(Command reply);
    }
}

class JobManager
{
    async Task ReportTrigger(Int32 triggerID)
    {
        await Task.Delay(300);
        await Webcam.CapturePhotoToFile();
        await Task.Delay(100);
    }
}

class WebCam
{
    async Task CapturePhotoFile()
    {
        await m_MediaCapture.CapturePhotoToStorageFileAsync( ImageEncodingProperties.CreateJpeg(), file );
    }
}

我真的需要确保在保存网络摄像头图片后正在执行调用“SendCommand(命令回复)”。 哪种方法更适合此目的?

在此先感谢并致以最诚挚的问候!

编辑:

根据收到的评论,我目前正在考虑这个实现:

class Core
{
    async Task ProcessCommandAsync(Command cmd)
    {
        // Do some stuff
        await JobManager.ReportTriggerAsync(cmd.TriggerID);
        SendCommand(Command reply);
    }
}

class JobManager
{
    async Task ReportTriggerAsync(Int32 triggerID)
    {
        await Task.Delay(300);
        await Webcam.CapturePhotoToFileAsync();
        await Task.Delay(100);
    }
}

class WebCam
{
    async Task CapturePhotoFileAsync()
    {
        await m_MediaCapture.CapturePhotoToStorageFileAsync( ImageEncodingProperties.CreateJpeg(), file );
    }
}

如果有人能确保我实现此实现的预期行为,我将不胜感激。 是否真的确定 Core.ProcessCommandAsync 中的命令是在图片保存后发送的?

@Dai:感谢您的反馈。 我将我的答案合并到我的第一个帖子中。 抱歉,添麻烦了。

有一些规则可以使异步更容易正确。

  1. 异步函数返回 Task 或 Task<>(不要使用 void)
  2. 异步函数以 Async 结尾 (MyFuncAsync) - 这提醒您在这些函数上调用 await,请参阅规则 3。
  3. 等待任何异步函数(除非您希望它们并行运行)
  4. 不要破坏这些规则。

如果您已经违反了这些规则并且必须重构您的程序,那么遵守这些规则可能会很困难。

(这些规则有很多例外,但是如果您不知道自己在做什么,请尽量遵守规则)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM