This is a discussion on Using Thread in C#. within the C# Programming forums, part of the Software Development category; Hi, I want to give a brief explanation about Threading and how to use it in C# and what is ...
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| Hi, I want to give a brief explanation about Threading and how to use it in C# and what is this usage. C# program starts in a single thread created automatically by the CLR and operating system (the "main" thread), and is made multi-threaded by creating additional threads. Namespace: using System; using System.Threading;
__________________ S.Balasubramanian Nothing is impossible |
| Sponsored Links |
| |||
| Example: class ThreadTest { static void Main() { Thread t = new Thread (Function1); t.Start(); // Run Function1 on the new thread while (true) Console.Write ("X"); // Write 'X' forever } private static void Function1() { while (true) Console.Write ("y"); // Write 'y' forever } } Output: xxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy yyy xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyy yyy yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxx xxx xxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyy yyy yyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxx ... Explanation: The main thread creates a new thread t on which it runs a method that repeatedly prints the character y. Simultaneously, the main thread repeatedly prints the character x.
__________________ S.Balasubramanian Nothing is impossible |
| |||
| Calling a function from Main method and a new thread: static void Main() { Thread t = new Thread(new ThreadStart(PrintX)); t.Start(); // Call PrintX() on a new thread PrintX(); // Call PrintX() on the main thread } static void PrintX() { for (int i= 0; i< 5; i++) Console.Write ('x'); } Output: xxxxxxxxxx
__________________ S.Balasubramanian Nothing is impossible |
| |||
| Passing Data to ThreadStart using ParameterizedThreadStart: class ThreadTest { static void Main() { Thread t = new Thread (new ParameterizedThreadStart(PrintX)); t.Start (true); } static void PrintX(object case) { bool case= (bool) case; Console.WriteLine (case? "UPPERCASE!" : "lowercase!"); } A feature of using ParameterizedThreadStart is that we must cast the object argument to the desired type (in this case bool) before use
__________________ S.Balasubramanian Nothing is impossible Last edited by Balasubramanian.S : 02-12-2008 at 01:16 AM. |
| |||
| Passing Data to ThreadStart in Normal Way: class ThreadTest { static void Main() { Thread t = new Thread (PrintX); t.Start (true); // == Go (true) PrintX(false); } static void PrintX(object case) { bool case= (bool) case; Console.WriteLine (case? "UPPERCASE!" : "lowercase!"); }
__________________ S.Balasubramanian Nothing is impossible |
| |||
| Another common system for passing data to a thread is by giving Thread an instance method rather than a static method. The instance object’s properties can then tell the thread what to do, as in the following rewrite of the original example: class ThreadTest { bool flag; static void Main() { ThreadTest threadTest1 = new ThreadTest(); threadTest1.flag= true; Thread t = new Thread (threadTest1 .PrintX); t.Start(); ThreadTest threadTest2 = new ThreadTest(); threadTest2.PrintX(); // Main thread – runs with flag=false } static void PrintX() { Console.WriteLine (flag? "UPPERCASE!" : "lowercase!"); }
__________________ S.Balasubramanian Nothing is impossible |
| |||
| Naming Threads: A thread can be named via its Name property. This is of great benefit in debugging: as well as being able to Console.WriteLine a thread’s name, Microsoft Visual Studio picks up a thread’s name and displays it in the Debug Location toolbar. A thread’s name can be set at any time – but only once – attempts to subsequently change it will throw an exception. The application’s main thread can also be assigned a name – in the following example the main thread is accessed via the CurrentThread static property: class NamingThread { static void Main() { Thread.CurrentThread.Name = "MainThread"; Thread worker = new Thread (Go); worker.Name = "worker"; worker.Start(); Go(); } static void Go() { Console.WriteLine ("This is from " + Thread.CurrentThread.Name); } } Output: This is from MainThread This is from worker
__________________ S.Balasubramanian Nothing is impossible |
| |||
| Foreground and Background Threads By default, threads are foreground threads, meaning they keep the application alive for as long as any one of them is running. C# also supports background threads, which don’t keep the application alive on their own – terminating immediately once all foreground threads have ended. Changing a thread from foreground to background doesn’t change its priority or status within the CPU scheduler in any way. A thread's IsBackground property controls its background status, as in the following example: class PriorityTest { static void Main (string[] args) { Thread worker = new Thread (delegate() { Console.ReadLine(); }); if (args.Length > 0) worker.IsBackground = true; worker.Start(); } }
__________________ S.Balasubramanian Nothing is impossible |
| |||
| Thread Priority A thread’s Priority property determines how much execution time it gets relative to other active threads in the same process, on the following scale: enum ThreadPriority { Lowest, BelowNormal, Normal, AboveNormal, Highest } This becomes relevant only when multiple threads are simultaneously active. Setting a thread’s priority to high doesn’t mean it can perform real-time work, because it’s still limited by the application’s process priority. To perform real-time work, the Process class in System.Diagnostics must also be used to elevate the process priority as follows (I didn't tell you how to do this): Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
__________________ S.Balasubramanian Nothing is impossible |
| |||
| Thread Synchronization: A multithreaded application usually has resources that can be accessed from multiple threads; for example, a global variable that is incremented or decremented by multiple threads. It is sometimes desirable to prevent multiple threads from concurrently altering the state of a resource. The .NET Framework includes several classes and data types that we can use to synchronize actions performed by two threads. The simplest case is if we have a shared variable that we need to update from different threads. To do this, we can use the System.Threading.Interlocked class. For example, to increment or decrement the shared variable called num, we'd write Interlocked.Increment(num) or Interlocked.Decrement(num). we can also use Interlocked to set the variables to a specific value or to check the equality of two variables.
__________________ S.Balasubramanian Nothing is impossible |
| |||
| Concurrency : When two threads change the same data, bad things can happen. In the following example two threads increment and then decrement a global variable. using System; using System.Threading; public class ThreadTest2 { public class Test { public static int counter = 0; public int repetitions=100; public void runme() { for(int i=0;i<repetitions;i++) { counter++; counter--; } Console.WriteLine(Thread.CurrentThread.Name+": "+counter); } } public static void Main(string[] args) { Test test = new Test(); Thread thread = new Thread(new ThreadStart(test.runme)); thread.Name = "first"; Test test1 = new Test(); Thread thread1 = new Thread(new ThreadStart(test1.runme)); thread1.Name = "second"; thread.Start(); thread1.Start(); } } Output: The results can be: first: 0 second: 0 or sometimes first: 1 second: 0
__________________ S.Balasubramanian Nothing is impossible |
| |||
| Threading.Interlocked methods : Using Threading.Interlocked.Increment the CLR will guarentee an atomic operation. Another interesting method in the namespace is "Exchange()" which swaps two values atomically. public class ThreadTest { public static int counter = 0; public int repetitions=100; public void runme() { for(int i=0;i<repetitions;i++) { System.Threading.Interlocked.Increment(ref i); System.Threading.Interlocked.Decrement(ref i); } Console.WriteLine(Thread.CurrentThread.Name+": "+counter); } } The results will be: first: 0 second: 0
__________________ S.Balasubramanian Nothing is impossible |
| |||
| Accessing problem : If you access the main thread controls from the user thread it raises the exception. So, you can use the following method to solve the error. private void Sample() { if (label1.InvokeRequired) { label1.Invoke(new MethodInvoker(Sample)); } else { if (label1.Visible == true) { label1.Visible = false; } else { label1.Visible = true; } } }
__________________ S.Balasubramanian Nothing is impossible |
| |||
| Here is just a basic example for how to use threads. using System; using System.Threading; namespace ThreadingExample { class ThreadingExample { public void Main(String[] args) { Console.WriteLine(”Starting…”); Thread myThread = new Thread(myThreadedMethod); myThread.Start(); while (true) { // do stuff here } } public void myThreadedMethod() { while(true) { //do other stuff here too } } } } |
| |||
| Advantages and Disadvantages of Multithreading : The following are the major advantages of using Multithreading. · Improved responsiveness · Faster execution · Better CPU and Memory utilization · Support for Concurrency The following are the drawbacks of using threads. · Problems in testing and debugging due to the non – deterministic nature of execution · Complexity
__________________ S.Balasubramanian Nothing is impossible |
![]() |
| Thread Tools | |
| Display Modes | |
| |
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| what is thread safe in java? | saravanan | Java Programming | 1 | 03-26-2008 02:08 AM |
| Process & Thread | Sathish Kumar | C# Programming | 4 | 08-22-2007 04:47 AM |
| How can we know a state of a thread in Dot Net? | bluesky | C# Programming | 1 | 07-25-2007 06:00 AM |
| What is daemon thread and How to create the daemon thread Java? | bluesky | Java Programming | 1 | 07-25-2007 05:55 AM |
| how many ways we can create a thread? | leoraja8 | Java Programming | 1 | 05-21-2007 03:57 AM |