Home > Blockchain >  Is there any way to stop the UI window instance of WPF
Is there any way to stop the UI window instance of WPF

Time:12-02

When I'm sending the data on a server and server is not up then I get an exception Unable to connect to the server and the UI window instance is closed while executing the line of code : (response = await client.PostAsJsonAsync("windows/actions", data).ConfigureAwait(false);). How can I stop the UI window it should not be closed.

My code :

        public static async void PostInfo(List<ElementProps> requestObj)
    {
    try
        {
        HttpResponseMessage response;
        using (HttpClient client = new HttpClient())
            {
            // Setting Base address. 
            client.BaseAddress = new Uri("http://126.1.1.1:8888/"); 

            // Setting content type.
            client.DefaultRequestHeaders.Accept.Add(new 
            MediaTypeWithQualityHeaderValue("application/json"));

            string list = JsonConvert.SerializeObject(requestObj); 
            object data = JsonConvert.DeserializeObject(list); 

            // HTTP POST ** Here is the error **
            response = await client.PostAsJsonAsync("windows/actions", data).ConfigureAwait(false); 

            // Verification
            if (response.IsSuccessStatusCode)
            { 
                 System.Windows.MessageBox.Show("Recording saved successfully!"); <br/>
            } 
        } 
    } 

    catch (Exception ex) 
    { 
         MessageBox.Show(ex.Message);
         ErrorLog.Log(ex);
    } 
}

CodePudding user response:

My main thread exits before the http client async operation finishes.

I just add .Wait() to caller to maintain the main thread. So, I have this :

PostInfo(Records).Wait();
  • Related