Skip to content

Instantly share code, notes, and snippets.

@aetos382 aetos382/wpfapm.cs
Last active Sep 16, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.