Last active
September 16, 2015 03:40
-
-
Save aetos382/0c803661e991ea8b31d4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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