Home > database >  async Task crashes application
async Task crashes application

Time:11-01

I have the following 2 methods, CheckForUpdatesExecute() is called when my ViewModel loads, which in turn calls GetLAtestVErsionAsync()

       private async void CheckForUpdatesExecute()
        {
            char[] MyChar = { 'v' };
            var _latestVersionFull = await GetLatestVersionAsync();
            var _latestVersion = _latestVersionFull.TrimStart(MyChar);
            Version latestVersion = new Version(_latestVersion);
            _updatesAvailable = latestVersion > CurrentVersion;
            ((DelegateCommand)InstallUpdate).RaiseCanExecuteChanged();
        }
        private async Task<string> GetLatestVersionAsync()
        {
            try
            {
                var client = new HttpClient();
                client.DefaultRequestHeaders.Accept.TryParseAdd("application/vnd.github json");
                client.DefaultRequestHeaders.UserAgent.TryParseAdd("Test");

                var stream = await client.GetStreamAsync("https://api.github.com/repos/<ORG>/<REPO>/releases/latest");
                var document = await JsonDocument.ParseAsync(stream);
                if (!document.RootElement.TryGetProperty("tag_name", out var tagNameProperty))
                {
                    return "0.0.0.0";
                }

                return tagNameProperty.GetString();
            }
            catch
            {
                return "0.0.0.0";
            }
        }

If I throw in a breakpoint here, I can see the app crashing/locking up with no error or exception displayed.

var stream = await client.GetStreamAsync("https://api.github.com/repos/<ORG>/<REPO>/releases/latest");

I had toyed with changing async void to async task, but from what I understand Task requires a return and I have nothing to return.

CodePudding user response:

Please try changing below code:

var stream = await client.GetStreamAsync("https://api.github.com/repos/<ORG>/<REPO>/releases/latest");

to

var stream = await client.GetStreamAsync("https://api.github.com/repos/<ORG>/<REPO>/releases/latest").ConfigureAwait(false);

Please refer to ConfigureAwait.

  • Related