15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The Thread Class ❘ 497<br />

For passing data to a thread, a class or struct that holds the data is needed. Here, the struct Data containing<br />

a string is defined, but you can pass any object you want:<br />

public struct Data<br />

{<br />

public string Message;<br />

}<br />

code snippet ThreadSamples/Program.cs<br />

If the ParameterizedThreadStart delegate is used, the entry point of the thread must have a parameter of<br />

type object <strong>and</strong> a void return type. The object can be cast to what it is, <strong>and</strong> here the message is written to<br />

the console:<br />

static void ThreadMainWithParameters(object o)<br />

{<br />

Data d = (Data)o;<br />

Console.WriteLine("Running in a thread, received {0}", d.Message);<br />

}<br />

With the constructor of the Thread class, you can assign the new entry point ThreadMainWithParameters<br />

<strong>and</strong> invoke the Start() method, passing the variable d:<br />

static void Main()<br />

{<br />

var d = new Data { Message = "Info" };<br />

var t2 = new Thread(ThreadMainWithParameters);<br />

t2.Start(d);<br />

}<br />

Another way to pass data to the new thread is to define a class (see the class MyThread), where you define<br />

the fields that are needed as well as the main method of the thread as an instance method of the class:<br />

public class MyThread<br />

{<br />

private string data;<br />

}<br />

public MyThread(string data)<br />

{<br />

this.data = data;<br />

}<br />

public void ThreadMain()<br />

{<br />

Console.WriteLine("Running in a thread, data: {0}", data);<br />

}<br />

This way, you can create an object of MyThread <strong>and</strong> pass the object <strong>and</strong> the method ThreadMain() to the<br />

constructor of the Thread class. The thread can access the data.<br />

background Threads<br />

var obj = new MyThread("info");<br />

var t3 = new Thread(obj.ThreadMain);<br />

t3.Start();<br />

The process of the application keeps running as long as at least one foreground thread is running. If more<br />

than one foreground thread is running <strong>and</strong> the Main() method ends, the process of the application remains<br />

active until all foreground threads finish their work.<br />

A thread you create with the Thread class, by default, is a foreground thread. Thread pool threads are<br />

always background threads.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!