使用 c# windows 形式的异步

Using async with c# windows form

我刚开始使用 API 对我来说太简单了。我正在尝试使用 Bing 图片搜索 API 将 3 张图片加载到图片框中,但我在使用异步方法时遇到了问题。从我的 POV 来看,一切看起来都应该工作得很好。 (我将此文档用于我的代码 https://docs.microsoft.com/en-us/bing/search-apis/bing-image-search/quickstarts/sdk/image-search-client-library-csharp)。任何建议将不胜感激。

    private static string _subscriptionKey = "MY_API_KEY";
    private static string _baseUri = "https://api.bing.microsoft.com/v7.0/images/search";    
    private static string searchString = "car";
    private static string _clientIdHeader = null;
    private const string QUERY_PARAMETER = "?q=";  // Required
    private const string MKT_PARAMETER = "&mkt=";  // Strongly suggested
private void searchButton_Click(object sender, EventArgs e)
    {
        RunAsync().Wait();

        static async Task RunAsync()
        {

            try
            {

                // Remember to encode the q query parameter.
                var queryString = QUERY_PARAMETER + Uri.EscapeDataString(searchString);
                queryString += MKT_PARAMETER + "en-us";
                HttpResponseMessage response = await MakeRequestAsync(queryString);
                _clientIdHeader = response.Headers.GetValues("X-MSEdge-ClientID").FirstOrDefault();
                // This example uses dictionaries instead of objects to access the response data.
                var contentString = await response.Content.ReadAsStringAsync();
                Dictionary<string, object> searchResponse = JsonConvert.DeserializeObject<Dictionary<string, object>>(contentString);
                if (response.IsSuccessStatusCode)
                {
                    PrintImages(searchResponse);
                }
            }
            catch (Exception)
            {
            }

            async Task<HttpResponseMessage> MakeRequestAsync(string queryString)
            {
                string count = "3";
                string offset = "0";

                var client = new HttpClient();
                
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", _subscriptionKey);
                return await client.GetAsync(string.Format("{0}q={1}&count={1}", _baseUri + queryString, count, offset));
            }


            void PrintImages(Dictionary<string, object> response)
            {
                
                var images = response["value"] as Newtonsoft.Json.Linq.JToken;
                foreach (Newtonsoft.Json.Linq.JToken image in images)
                {
                    string imagePic = (image["contentUrl"]).ToString();
                    optionOnePicture.ImageLocation = imagePic;
                    optionTwoPicture.ImageLocation = imagePic;                      
                    optionThreePicture.ImageLocation = imagePic;                      
               
                }
            }

        }

Don't block on async code。相反,使用 await:

private async void searchButton_Click(object sender, EventArgs e)
{
  await RunAsync();
  ...
}

旁注:此代码使用 async void 因为该方法是事件处理程序。通常,您会想要 avoid async void.