強制停止正在執行的方法


摘要:如何暴力停止當前正在執行中的方法?利用線程強制退出,終止當前方法的執行。可以用於用戶頻繁操作UI請求后台服務,操作耗時等業務場景。

廢話不說,上代碼

 1  /// <summary>
 2     /// 可強制終止執行的方法。用在比較耗時的操作沒有結果的時候,強制退出上次的執行操作,以確保本次正確執行
 3     /// </summary>
 4     public class TerminableMethod
 5     {
 6         private System.Threading.Thread _thread = null;
 7 
 8         private Action<object> _action;
 9 
10         public TerminableMethod(Action<object> action)
11         {
12             this._action = action;
13         }
14 
15         /// <summary>
16         /// 啟用方法,一定覆蓋上次執行
17         /// </summary>
18         /// <param name="parameter"></param>
19         public void Start(object parameter)
20         {
21             try
22             {
23                 if (_thread != null)
24                 {
25                     _thread.Abort();
26                     _thread = null;
27                 }
28                 _thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(_action));
29                 _thread.IsBackground = true;
30                 _thread.Start(parameter);
31             }
32             catch (Exception ex)
33             {
34                 Console.WriteLine("啟用方法異常!" + ex.Message);
35                 throw ex;
36             }
37         }
38     }

使用:

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             TerminableMethod methodAbort = new TerminableMethod(MethodAbortTest);
 6             Task.Run(() =>
 7             {
 8                 while (true)
 9                 {
10                     var r = new System.Random(Guid.NewGuid().GetHashCode());
11                     var max = r.Next(100, 300);
12                     methodAbort.Start(max);
13                     System.Threading.Thread.Sleep(5);
14                 }
15             });
16             Console.ReadLine();
17         }
18 
19         static void MethodAbortTest(object obj)
20         {
21             int maxVal = (int)obj;
22             Console.WriteLine("開始執行任務!");
23             int i = 0;
24             while (i++ < maxVal)
25             {
26                 Console.WriteLine("當前執行任務:" + i);
27                 System.Threading.Thread.Sleep(1);
28             }
29             Console.WriteLine("執行任務結束!");
30         }
31     }

注意:每次執行TerminableMethod.Start,都能確保本次流程從頭開始。所以每次操作前,需要對上次操作的資源進行初始化。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM