【发布时间】:2022-01-06 06:24:17
【问题描述】:
当我在服务器上发送数据并且服务器未启动时,我得到一个异常 Unable to connect to the server 并且 UI 窗口实例在执行代码行时关闭: (response = await client.PostAsJsonAsync("windows/actions", data).ConfigureAwait(false);)。如何停止不应关闭的 UI 窗口。
我的代码:
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);
}
}
【问题讨论】:
-
请编辑您的问题,以更易读的格式包含您的代码(并且不要为您的问题文本添加不必要的粗体)。有关编辑指导,请参阅 stackoverflow.com/editing-help。
-
请下次从文本编辑器中复制代码,而不是浏览器等。
<br/>不属于代码。 -
确定我会从下一次开始处理这个问题。感谢@PMF的建议
-
在这种情况下,您的程序应该进入 catch 块。但是由于
ConfigureAwait(false),您可能不再在UI线程上,因此MessageBox.Show可能会失败。 -
No MessageBox.show 不会失败它会显示异常但我需要停止 UI 窗口实例。
标签: c# http xmlhttprequest dotnet-httpclient