Passing Data to Thread in C#
Delegate is just a function call and it must have same signature as actual function it is trying to call.
namespace Threadsspace.BasicDelegate
{
// Declaration
public delegate void SimpleDelegate();
class TestDelegate
{
public static void MyFunction()
{
Console.WriteLine("Call to delegate ...");
}
public static void Main()
{
// Instantiate
SimpleDelegate mySimpleDelegate = new SimpleDelegate(MyFunc);
// Invocate
mySimpleDelegate();
}
}
}
So what we have is function of some sort that displays threads
static void WorkWithParam(object o)
{
string info = (string) o;
for (int x = 0; x < 10; ++x)
{
Console.WriteLine("{0}: {1}", info, Thread.CurrentThread.ManagedThreadId);
// Slow down
Thread.Sleep(10);
}
}
ParameterizedThreadStart myOperation = new ParameterizedThreadStart(WorkWithParam);
// Creates
Thread theMainThread = new Thread(myOperation);
// Start
theMainThread.Start("Hell");
// 2nd Thread
Thread MyNewThread = new Thread(myOperation);
MyNewThread.Start("Good");
If we want to stop Thread we must issue command Thread.Abort When we abort the thread it does not know at what point it is safe to abort so we always have to provide regions within our methods
Thread newMyThread = new Thread(new ThreadStart(AbortThread));
newMyThread.Start();
newMyThread.Abort();
static void AbortThread()
{
// Set the data
Thread.BeginCriticalRegion();
SomeClass.IsValid = true;
SomeClass.IsComplete = true;
Thread.EndCriticalRegion();
// Write the object
SomeClass.WriteToConsole();
}
Each thread has data associated with it and this data travels from thread to thread and if we want to increase performance we need to suppress this information information flow with the help of ExecutionContext.SuppressFlow
AsyncFlowControl myFlowControl = ExecutionContext.SuppressFlow();
// New thread
Thread myThread = new Thread(new ThreadStart(SomeWork));
myThread.Start();
myThread.Join();
// Restore
ExecutionContext.RestoreFlow();
// could flow.Undo();