IMHOTEP Framework
 All Classes Namespaces Functions Variables Enumerations Enumerator Properties Pages
ThreadUtil.cs
1 /*
2 
3 ::::::::::::::::::::::::Examlpe::::::::::::::::::::::::
4 
5 public class Worker
6 {
7  //Threaded method
8  public void DoWork(object sender, DoWorkEventArgs e)
9  {
10  BackgroundWorker worker = sender as BackgroundWorker;
11  for (int i = 0; i < int.MaxValue; i++)
12  {
13  if (worker.CancellationPending)
14  {
15  e.Cancel = true;
16  break;
17  }
18 
19  //-------------------DO A LOT OF WORK-------------------
20 
21  }
22  }
23 
24  //Callback method
25  public void Callback(object sender, RunWorkerCompletedEventArgs e)
26  {
27  BackgroundWorker worker = sender as BackgroundWorker;
28  if (e.Cancelled)
29  {
30  //-------------------Handle cancellation-------------------
31  }
32  else if (e.Error != null)
33  {
34  //-------------------Handle error-------------------
35  }
36  else
37  {
38  //-------------------Handle correct completion-------------------
39  }
40 
41  }
42 
43  //Use ThreadUtil
44  static void Main(string[] args)
45  {
46  ThreadUtil t = new ThreadUtil(this.DoWork, this.Callback);
47  t.Run();
48 
49  if(t.IsBusy())
50  {
51  Console.WriteLine("Working");
52  }
53 
54 
55  }
56 }
57 
58 :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
59 
60 */
61 
62 
63 
64 using UnityEngine;
65 using System.ComponentModel;
66 using System;
67 
68 public class ThreadUtil {
69 
70  BackgroundWorker backgroundWorker;
71 
72 // private DoWorkEventHandler threadedMethod;
73  private RunWorkerCompletedEventHandler callbackMethod;
74 
75  //private DateTime start;
76 
77  public ThreadUtil(DoWorkEventHandler threadedMethod, RunWorkerCompletedEventHandler callbackMethod)
78  {
79  //this.threadedMethod = threadedMethod;
80  this.callbackMethod = callbackMethod;
81 
82  backgroundWorker = new BackgroundWorker();
83  //backgroundWorker.WorkerReportsProgress = true;
84  backgroundWorker.WorkerSupportsCancellation = true;
85  backgroundWorker.DoWork += new DoWorkEventHandler(threadedMethod);
86  backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Callback);
87  }
88 
89  private void Callback(object sender, RunWorkerCompletedEventArgs e)
90  {
91  callbackMethod(sender, e);
92  //Debug.Log("[ThreadUtil] Thread finished - duration: " + (DateTime.Now - start));
93  }
94 
95  public void Run()
96  {
97  //start = DateTime.Now;
98  backgroundWorker.RunWorkerAsync();
99  //Debug.Log("[ThreadUtil] Thread started");
100  }
101 
102  /*
103  You have to implement the canclellation in your DoWork-method. If DoWorkEventArgs.Cancel = true, abort the method;
104  */
105  public void Abort()
106  {
107  backgroundWorker.CancelAsync();
108  //Debug.Log("[ThreadUtil] Thread aborted");
109  }
110 
111  public bool IsBusy()
112  {
113  return backgroundWorker.IsBusy;
114  }
115 }