Home > Software design >  How do I force a wait in the C# async await model
How do I force a wait in the C# async await model

Time:01-31

I think I must be missing something with my understanding of the async await model. What should be a simple thing seems to be unbelievably hard to achieve.

I have a UI which needs to check if the user is logged in. To do this I need to call a method in one of my classes which does some queries.

This class in turn calls 3rd party code which only has async methods.

How can I call that async method and make the application wait until I get a result?

I have tried all the things suggested such as ConfigureAwait, RunSynchronous, .Result, etc.. Nothing seems to reliably work.

It seems so stupid that something like this is so difficult so I assume I am missing a key piece of information.

Thanks.

CodePudding user response:

Lets make something clear:

"make the application wait until I get a result?"

Has nothing to do (I cannot stress this enough) with blocking, awaiting or any result whatsoever.

If you are used of making the UI lock until something is done, you should switch your design, instead of trying to find a way to accomplish it. (I have spent fair amount of time writing MFC apps for Windows Mobile, I used to do this as well)

The correct way to handle such situation, is to let the user know, that there is work being done (Some sort of Activity Indicator for example), and at the same time, make sure that no other code can be executed due to User Input (CanExecute property of your Command for example). When it is appropriate, you can put Cancelation logic.

Even more, in the context of MAUI (and mobile development in general), blocking the UI thread, even for few seconds, is totally not acceptable. It should remain responsive at all times. This is not a matter of choice.

CodePudding user response:

You can use the Task.Result in the property to block the calling thread until the Task is completed. However, this is not recommended in most cases because it can lead to deadlocks. A better approach is to use await in a method marked as async, which will cause the method to return control to the calling method until the awaited Task is completed. If you need to block the thread, consider using ConfigureAwait(false) when awaiting the Task. Read this for further information about the synchronous error handling to Async / Callback programs.

  • Related