簡體   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