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();
これがフォーム/コントロールの場所