Ad

How To Call Async Function With Await Inside A Non Async Function In C#?

- 1 answer

I have an async function call myAsyncfuntion() which look like that

public async Task TakePhotoBasicAndSaveAndDisplayUWP()
{
    var photoImplementation = new MediaCaptureImplementation();
    photoImplementation.TakePhotoTexture2DAsync();
    // Some code here...

    await photoImplementation.SavePhotoToPicturesLibraryAsync();
}

Now I would like to call this function from another non async function so I do like this. Basically I attact a button to TakePhotoBasicAndSaveAndDisplay() and whenever the button got clicked, the function will start the async function inside. But the async function seem not to be called.

public void TakePhotoBasicAndSaveAndDisplay()
{
   #if WINDOWS_UWP
    var task = Task.Run(async () => await TakePhotoBasicAndSaveAndDisplayUWP());
   #endif
}

Could anyone help me ? I am working with unity

Ad

Answer

As Marc commented, the only correct answer to "how do I call an asynchronous method from a synchronous method" is "you don't".

But the async function seem not to be called.

It is certainly being called, but it's possible that it may not be working correctly because it is not on the main UI thread. Task.Run is executing it on a thread pool thread. Also, I suspect that the task in var task = Task.Run(async () => await TakePhotoBasicAndSaveAndDisplayUWP()); is never awaited, so any exceptions from TakePhotoBasicAndSaveAndDisplayUWP would be ignored. I.e., exceptions stating that some API must be called from the main UI thread and not a thread pool thread.

I attact a button to TakePhotoBasicAndSaveAndDisplay

If TakePhotoBasicAndSaveAndDisplay is in fact an event handler, then you can use async void:

public async void TakePhotoBasicAndSaveAndDisplay()
{
  #if WINDOWS_UWP
  await TakePhotoBasicAndSaveAndDisplayUWP();
  #endif
}
Ad
source: stackoverflow.com
Ad