WPF程序中,代码运行this.Close()后,窗体内代码仍然会持续运行,直到遇到i的一个异步调用,且该调用包含一个HttpWebRequest的请求,上述代码才会停止运行。
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
namespace WpfApp2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
Close();
var result = await Task.Run(() =>
{
var host_name = "localhost";
HttpWebRequest request = WebRequest.Create($"http://{host_name}:8080/rest/api/2/project/AS/components") as HttpWebRequest;
request.Method = "GET";
request.ContentType = "application/json";
var token = "Basic eGlhX3lhbmdqdW46Z3VvZmFuZw==";
if (!string.IsNullOrEmpty(token)) request.Headers[HttpRequestHeader.Authorization] = token;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
reader.Close();
}
return 123;
});
Console.WriteLine(123);
}
}
}