[英]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:感謝您的反饋。 我將我的答案合並到我的第一個帖子中。 抱歉,添麻煩了。
有一些規則可以使異步更容易正確。
如果您已經違反了這些規則並且必須重構您的程序,那么遵守這些規則可能會很困難。
(這些規則有很多例外,但是如果您不知道自己在做什么,請盡量遵守規則)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.