PageRenderTime 41ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/Code/Source/Teaching.Wpf.Threading/MainWindow.xaml.cs

https://bitbucket.org/BernhardGlueck/teaching
C# | 97 lines | 61 code | 10 blank | 26 comment | 2 complexity | 8b4797b880adf60c65cc0057e1eb2fa9 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Reactive.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows;
  10. using System.Windows.Controls;
  11. using System.Windows.Data;
  12. using System.Windows.Documents;
  13. using System.Windows.Input;
  14. using System.Windows.Media;
  15. using System.Windows.Media.Imaging;
  16. using System.Windows.Navigation;
  17. using System.Windows.Shapes;
  18. using Teaching.Core.Threading;
  19. namespace Teaching.Wpf.Threading
  20. {
  21. /// <summary>
  22. /// Interaction logic for MainWindow.xaml
  23. /// </summary>
  24. public partial class MainWindow : Window
  25. {
  26. public MainWindow()
  27. {
  28. InitializeComponent();
  29. }
  30. private void DownloadButton_Click(object sender, RoutedEventArgs e)
  31. {
  32. if ( string.IsNullOrWhiteSpace(UrlTextBox.Text))
  33. {
  34. return;
  35. }
  36. var url = UrlTextBox.Text;
  37. // AMI based ( < NET 4.0 )
  38. var amiRequest = WebRequest.Create(url);
  39. amiRequest.BeginGetResponse(state =>
  40. {
  41. var response = amiRequest.EndGetResponse(state);
  42. using( var responseStream = response.GetResponseStream())
  43. {
  44. var content = new StreamReader(responseStream).ReadToEnd();
  45. if (!Dispatcher.CheckAccess())
  46. {
  47. Dispatcher.Invoke(() => ContentTextBox.Text = content);
  48. }
  49. else
  50. {
  51. UrlTextBox.Text = content;
  52. }
  53. }
  54. }, null);
  55. // Threading based ( < NET 4.0 )
  56. /*var downloadThread = new DisposableThread(c =>
  57. {
  58. var content = new WebClient().DownloadString(url);
  59. if ( !Dispatcher.CheckAccess())
  60. {
  61. Dispatcher.Invoke(() => ContentTextBox.Text = content);
  62. }
  63. else
  64. {
  65. UrlTextBox.Text = content;
  66. }
  67. });
  68. downloadThread.Execute();*/
  69. // TPL based ( NET 4.0 )
  70. /*new WebClient().DownloadStringTaskAsync(url).ContinueWith(d =>
  71. {
  72. this.ContentTextBox.Text = d.Result;
  73. }, TaskScheduler.FromCurrentSynchronizationContext());*/
  74. #pragma warning disable 4014
  75. // Async ( NET 4.5 )
  76. DownloadContent(url);
  77. #pragma warning restore 4014
  78. }
  79. private async Task DownloadContent(string url)
  80. {
  81. var result = await new WebClient().DownloadStringTaskAsync(url);
  82. ContentTextBox.Text = result;
  83. }
  84. }
  85. }