1

I am writing an AddIn for ArcGIS 10.x using C#. I want to asynchronously download a file within ArcMap using HttpClient. My test code works in a hello world app but just hangs when I debug it in ArcMap.

Is it possible to write multi-threaded code using async within ArcMap AddIns?

private static async Task<raveInfo> GetLatestVersion(string url, HttpClient client)
    {
        client.DefaultRequestHeaders.UserAgent.TryParseAdd("request");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.ConnectionClose = true;

        using (var httpResponse = await client.GetAsync(url))
        {
            httpResponse.EnsureSuccessStatusCode(); // throws if not 200-299

            if (httpResponse.Content is object && httpResponse.Content.Headers.ContentType.MediaType == "application/json")
            {
                var contentStream = await httpResponse.Content.ReadAsStreamAsync();
                using (var streamReader = new StreamReader(contentStream))
                {
                    using (var jsonReader = new JsonTextReader(streamReader))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        try
                        {
                            return serializer.Deserialize<raveInfo>(jsonReader);
                        }
                        catch (JsonReaderException)
                        {
                            throw new Exception("Invalid JSON.");
                        }
                    }
                }
            }
            else
            {
                throw new Exception("HTTP Response was invalid and cannot be deserialised.");
            }
        }

        return null;
    }
1
  • Have you tried searching this forum first? Lots on multi threading in arcmap, such as this.
    – Hornbydd
    Sep 7, 2021 at 23:23

1 Answer 1

1

I ended up using WebClient.

// http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/
using (WebClient webClient = new WebClient())
{
    webClient.DownloadFile(remotePath, localPath);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.