The Thread Class C# Help

With the Thread class you can create and control threads. The code here is a very simple example of creating and starting a new thread. The constructor of the Thread class accepts a delegate parameter
of type ThreadStart and Parameteri zedThreadStart. The ThreadStart delegate defines a method with a void return type and without arguments. After the Thread object is created, you can start the thread with the Start () method:

using System;
using System. Threading;
namespace Wrox.ProCSharp.Threading

When you run the application, you get the output of the two threads:

This is the ma~n thread.
Running in a thread.

There is no guarantee as to what output comes first. Threads are scheduled by the operating system; which thread comes first can be different each time.

You have seen how a Lambda expression can be used with an asynchronous delegate. You can use it with the Thread class as well by passing the implementation of the thread method to the argument of the Thread constructor:

using System;
using System.Threading;

If you don’t need a variable referencing the thread to control the thread object after it was created, you can also write the code in a shorter way. Create a new Thread object with the constructor, pass a Lambda
expression-to the constructor, and with the Th;-ead object returned, invoke the Start () method directly

There are some good reasons for having a variable to reference the Thread object. One example, for better control of the threads, is that you can assign a name to the thread by setting the Name propertybefore starting the thread. To get the name of the current thread, you can use the static property Thread. CurrentThread to get to the Thread instance of the current thread and access the Name property for read access. The thread also has a managed thread ID that you can read with the property ManagedThreadId.

With the .output of the application, you can also see the thread name and 10:

This is the main thread.
Running in the thread MyNewThreadl, id: 3.

Passing Data to.Threads

There are two ways to pass some data to a thread. You can either use the Thread constructor with the Parametric Thread Start delegate, or you can create a custom class and define the method of the thread as an instance method so that Y0′:l can initialize data of the instance before starting the thread. For passing data to a thread, any class or struct that holds the data is needed. Here, the struct Data containing a string is defined, but you can pass any object you want:


Posted on November 3, 2015 in Threading and Synchronization

Share the Story

Back to Top