BackgroundWorker.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. //
  2. // BackgroundWorker.cs
  3. //
  4. // Authors:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2006 Novell, Inc.
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. #if NET_2_0
  30. using System.Collections.Generic;
  31. using System.Threading;
  32. namespace System.ComponentModel
  33. {
  34. [DefaultEvent ("DoWork")]
  35. public class BackgroundWorker : Component
  36. {
  37. public BackgroundWorker ()
  38. {
  39. }
  40. AsyncOperation async;
  41. bool cancel_pending, report_progress = false, support_cancel = false;
  42. Dictionary<object,AsyncOperation> operations =
  43. new Dictionary<object,AsyncOperation> ();
  44. public event DoWorkEventHandler DoWork;
  45. public event ProgressChangedEventHandler ProgressChanged;
  46. public event RunWorkerCompletedEventHandler RunWorkerCompleted;
  47. [Browsable (false)]
  48. public bool CancellationPending {
  49. get { return cancel_pending; }
  50. }
  51. [Browsable (false)]
  52. public bool IsBusy {
  53. get { return async != null; }
  54. }
  55. [DefaultValue (false)]
  56. public bool WorkerReportsProgress {
  57. get { return report_progress; }
  58. set { report_progress = value; }
  59. }
  60. [DefaultValue (false)]
  61. public bool WorkerSupportsCancellation {
  62. get { return support_cancel; }
  63. set { support_cancel = value; }
  64. }
  65. public void CancelAsync ()
  66. {
  67. if (!support_cancel)
  68. throw new InvalidOperationException ("This background worker does not support cancellation.");
  69. if (!IsBusy)
  70. return;
  71. cancel_pending = true;
  72. async.PostOperationCompleted (delegate (object darg) {
  73. OnRunWorkerCompleted (
  74. new RunWorkerCompletedEventArgs (
  75. null, null, true));
  76. this.async = null;
  77. cancel_pending = false;
  78. },
  79. null);
  80. }
  81. public void ReportProgress (int percentProgress)
  82. {
  83. ReportProgress (percentProgress, null);
  84. }
  85. public void ReportProgress (int percentProgress, object userState)
  86. {
  87. if (!WorkerReportsProgress)
  88. throw new InvalidOperationException ("This background worker does not report progress.");
  89. // FIXME: verify the expected behavior
  90. if (!IsBusy)
  91. return;
  92. async.Post (delegate (object o) {
  93. ProgressChangedEventArgs e = o as ProgressChangedEventArgs;
  94. OnProgressChanged (e);
  95. },
  96. new ProgressChangedEventArgs (percentProgress, userState));
  97. }
  98. public void RunWorkerAsync ()
  99. {
  100. RunWorkerAsync (null);
  101. }
  102. delegate void ProcessWorkerEventHandler (object argument, AsyncOperation async, SendOrPostCallback callback);
  103. void ProcessWorker (object argument, AsyncOperation async, SendOrPostCallback callback)
  104. {
  105. // do worker
  106. Exception error = null;
  107. DoWorkEventArgs e = new DoWorkEventArgs (argument);
  108. try {
  109. OnDoWork (e);
  110. } catch (Exception ex) {
  111. error = ex;
  112. }
  113. callback (new object [] {
  114. new RunWorkerCompletedEventArgs (
  115. e.Result, error, e.Cancel),
  116. async});
  117. }
  118. void CompleteWorker (object state)
  119. {
  120. object [] args = (object []) state;
  121. RunWorkerCompletedEventArgs e =
  122. args [0] as RunWorkerCompletedEventArgs;
  123. AsyncOperation async = args [1] as AsyncOperation;
  124. SendOrPostCallback callback = delegate (object darg) {
  125. OnRunWorkerCompleted (darg as RunWorkerCompletedEventArgs);
  126. };
  127. async.PostOperationCompleted (callback, e);
  128. this.async = null;
  129. }
  130. public void RunWorkerAsync (object argument)
  131. {
  132. if (IsBusy)
  133. throw new InvalidOperationException ("The background worker is busy.");
  134. async = AsyncOperationManager.CreateOperation (this);
  135. ProcessWorkerEventHandler handler =
  136. new ProcessWorkerEventHandler (ProcessWorker);
  137. handler.BeginInvoke (argument, async, CompleteWorker, null, null);
  138. }
  139. protected virtual void OnDoWork (DoWorkEventArgs e)
  140. {
  141. if (DoWork != null)
  142. DoWork (this, e);
  143. }
  144. protected virtual void OnProgressChanged (ProgressChangedEventArgs e)
  145. {
  146. if (ProgressChanged != null)
  147. ProgressChanged (this, e);
  148. }
  149. protected virtual void OnRunWorkerCompleted (RunWorkerCompletedEventArgs e)
  150. {
  151. if (RunWorkerCompleted != null)
  152. RunWorkerCompleted (this, e);
  153. }
  154. }
  155. }
  156. #endif