Skip to content

Instantly share code, notes, and snippets.

@aetos382
Last active September 16, 2015 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aetos382/0c803661e991ea8b31d4 to your computer and use it in GitHub Desktop.
Save aetos382/0c803661e991ea8b31d4 to your computer and use it in GitHub Desktop.
private void button_Click(object sender, RoutedEventArgs e)
{
// ここは UI スレッドで実行される
Debug.WriteLine("button_Click : {0}", Thread.CurrentThread.ManagedThreadId);
var request = WebRequest.CreateHttp("http://tech.blog.aerie.jp");
request.BeginGetResponse(this.OnGetResponseCompleted, request);
}
private void OnGetResponseCompleted(IAsyncResult result)
{
// ここはワーカー スレッドで実行される
Debug.WriteLine("OnGetResponseCompleted : {0}", Thread.CurrentThread.ManagedThreadId);
var request = (HttpWebRequest)result.AsyncState;
using (var response = request.EndGetResponse(result))
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
string content = reader.ReadToEnd();
this.SetBrowserContent(content);
}
}
private void SetBrowserContent(string content)
{
Action action = () => this.webBrowser.NavigateToString(content);
if (this.Dispatcher.CheckAccess())
{
// 現在のスレッドが UI スレッドならそのまま実行
action();
}
else
{
// そうでなければ Dispatcher.Invoke で UI スレッドに処理を依頼する
this.Dispatcher.Invoke(action);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment