Firstly, let's focus on Thread Class which represents the main Class of our post. This class lets us do everything that we have discussed earlier like suspending, aborting, starting, prioritising and so on. I will demonstrate the rest of material in a video clip. some complementary information about the lifecycle of Threads in C#:
- Aborted - The thread is in the stopped state
- AbortRequested - The Abort() method has been called but the thread has not yet received the System.Threading.ThreadAbortexception that will try to terminate it - the thread is not stopped but soon will be.
- Background - The thread is being executed in the background
- Running - The thread has started and is not blocked
- Stopped - The thread has completed all its instructions and stopped
- Suspended - The thread has been suspended
- WaitSleepJoin - The thread has been blocked by a call to Wait(), Sleep(), or Join()
- Unstarted - The Start() method has not yet been called on the thread
for the first try, it is better to start off with a very simple code to see how two threads can work simultaneously. in this code sample, we have a Class called "work" that contains two methods.
the first thread works on the first method and the second one goes for the second method.
the difference between these two methods is, one meant for being used as a static method and another one is meant for using by an object of the class. after running both threads, their state becomes running till they finish. so the following code is all about the main function of our console application.
static void Main() { ThreadStart x = new ThreadStart(Work.DoWork); Thread newThread = new Thread(x); Work w = new Work(); w.Data = 42; ThreadStart x2 = new ThreadStart(w.DoMoreWork); Thread newThread2 = new Thread(x2); newThread.Start(); newThread2.Start(); Console.ReadLine(); }now it is the time for implementing our desired class ( word ).
class Work { public static void DoWork() { Console.WriteLine("Static thread procedure has run"); } public int Data; public void DoMoreWork() { Console.WriteLine("Instance thread procedure. data=> {0}", Data); } }if you run this program for several times, you may get several outputs as threads are not executing in the same order. hope this short tutorial would be beneficial to you guys.
references: C# threading handbook
No comments:
Post a Comment