Reputation: 133
please excuse the possibly stupid question. Is there a difference between the two code snippets?
Example 1: Running an async method CapturePhotoToStorageFileAsync in a synchronous method
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 );
}
}
Example 2: Running the async method CapturePhotoToStorageFileAsync as a task:
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 );
}
}
I really need to make sure that the Call "SendCommand(Command reply)" is being executed AFTER the webcam picture has been saved. Which method is more suitable for this purpose?
Thanks in advance and best regards!
EDIT:
According to the comments received i am currently thinking about this implementation:
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 );
}
}
I would really appreciate if somebody could ensure me the intended behaviour for this implementation. Is it really assured that the command in Core.ProcessCommandAsync is send AFTER the picture has been saved?
@Dai: Thanks for your feedback. I merged my answer into my first posting. Sorry for the trouble.
Upvotes: 0
Views: 1096
Reputation: 11889
There are a few rules that make async easier to get right.
Keeping to these rules can be hard, if you have already broken them, and have to refactor your program.
(there are lots of exceptions to these rules, but if you don't know what you are doing, then try to keep to the rules).
Upvotes: 3