More Group Sites
Education Books
School Rankings
Jobless Net
Better Home
Enviro++
更好教育论坛


Help | Subscribe/Unsubscribe | Rules | Other Group Sites: Better Education | Better Education Forum
Welcome Guest! To enable all features please Login or Register.

Notification

Icon
Error

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

Rank: Administration

Reputation:

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

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();
                    Task.WhenAll(t);
                    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, June 6, 2019 6:58:54 PM(UTC)  | Reason: Not specified

Sponsor
Rss Feed  Atom Feed
Users browsing this topic
Guest
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.