我不知道您使用的是 WPF 还是 Windows 窗体。这是一个 WPF 示例。
WebRequest w = HttpWebRequest.Create("http://www.google.com");
Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
Thread thread = new Thread(new ThreadStart(() =>
{
WebResponse response = w.GetResponse();
dispatcher.BeginInvoke(new Action(() =>
{
// Handle response on the dispatcher thread.
}), null);
}));
thread.IsBackground = true;
thread.Start();
注意 IsBackground = true。因此,您的应用程序将在退出时终止它。也可以将 HttpWebRequest.Create 放在线程方法中。
Windows.Form 等效项
WebRequest w = HttpWebRequest.Create("http://www.google.com");
Thread thread = new Thread(new ThreadStart(() =>
{
WebResponse response = w.GetResponse();
this.BeginInvoke(new Action(() =>
{
// Handle response on the dispatcher thread.
}), null);
}));
thread.IsBackground = true;
thread.Start();
这是一个表单/控件