More Group Sites
Education Books
School Rankings
Jobless Net
Better Home
Welcome Guest! To enable all features please Login or Register.



Go to last post Go to first unread
#1 Posted : Wednesday, 5 June 2019 5:34:49 PM(UTC)

Rank: Administration


Groups: AcademicCoachingSchool, admin, Administration, BookSeller, CatholicSchool, CoachingAdult, CoachingProfessional, CoachingSports, ExtraCurriculumCoaching, IndependentSchool, Moderator, MusicTeacher, PrivateSchool, PublicSchool, SelectiveSchool, tutor
Joined: 23/11/2008(UTC)
Posts: 523

C# How to call asynchronous method from synchronous method? - Use async HttpClient synchronously

Most of us would know that the potential deadlock can be caused by using .Wait() and .Result of asynchronous method from synchronous method. There are a lot of questions on this issue on internet. There are marked answers such as using .GetAwaiter().GetResult() or .ConfigureAwait(false). Does it help? Probably not. Keep trying. How about this?

                    var t = methodAsync();
                    var result = t.Result;

Still no luck.

Have you experienced the deadlock issues with calling asynchronous method from synchronous method?  There are many questions on StackOverflow. Many threads on this question actually have the wrong answer as the accepted answer, but it looks very similar to the right answer. That is, they skip the call to .Wait(). 

MSDN explicitly stated that running the task on a thread, waiting, and fetching the result after waiting is safe. See ASP.Net–Do not use Task .Result in main context.

The following method is completely deadlock free, the correct way.

            var task = Task.Run(() => _httpClient.PostAsync(url, encodedContent));

            if (!task.Wait(timeout))


                //Device.BeginInvokeOnMainThread is required

                Device.BeginInvokeOnMainThread(async () =>


                    //main thread methods, eg. update UI


                //handle time out


Use it only when you cannot use asynchronous method.

Edited by user Thursday, 6 June 2019 6:58:54 PM(UTC)  | Reason: Not specified

Rss Feed  Atom Feed
Users browsing this topic
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.