/Code/Source/Teaching.Wpf.Threading/MainWindow.xaml.cs
C# | 97 lines | 61 code | 10 blank | 26 comment | 2 complexity | 8b4797b880adf60c65cc0057e1eb2fa9 MD5 | raw file
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Reactive.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Navigation;
- using System.Windows.Shapes;
- using Teaching.Core.Threading;
-
- namespace Teaching.Wpf.Threading
- {
- /// <summary>
- /// Interaction logic for MainWindow.xaml
- /// </summary>
- public partial class MainWindow : Window
- {
- public MainWindow()
- {
- InitializeComponent();
- }
-
- private void DownloadButton_Click(object sender, RoutedEventArgs e)
- {
- if ( string.IsNullOrWhiteSpace(UrlTextBox.Text))
- {
- return;
- }
-
- var url = UrlTextBox.Text;
-
- // AMI based ( < NET 4.0 )
- var amiRequest = WebRequest.Create(url);
-
- amiRequest.BeginGetResponse(state =>
- {
- var response = amiRequest.EndGetResponse(state);
- using( var responseStream = response.GetResponseStream())
- {
- var content = new StreamReader(responseStream).ReadToEnd();
-
- if (!Dispatcher.CheckAccess())
- {
- Dispatcher.Invoke(() => ContentTextBox.Text = content);
- }
- else
- {
- UrlTextBox.Text = content;
- }
- }
- }, null);
-
- // Threading based ( < NET 4.0 )
- /*var downloadThread = new DisposableThread(c =>
- {
- var content = new WebClient().DownloadString(url);
-
- if ( !Dispatcher.CheckAccess())
- {
- Dispatcher.Invoke(() => ContentTextBox.Text = content);
- }
- else
- {
- UrlTextBox.Text = content;
- }
- });
-
- downloadThread.Execute();*/
-
- // TPL based ( NET 4.0 )
- /*new WebClient().DownloadStringTaskAsync(url).ContinueWith(d =>
- {
- this.ContentTextBox.Text = d.Result;
- }, TaskScheduler.FromCurrentSynchronizationContext());*/
-
- #pragma warning disable 4014
- // Async ( NET 4.5 )
- DownloadContent(url);
- #pragma warning restore 4014
- }
-
- private async Task DownloadContent(string url)
- {
- var result = await new WebClient().DownloadStringTaskAsync(url);
- ContentTextBox.Text = result;
- }
- }
- }