Share data between threads via instance method
class ShareDataInstanceVariable
{
string instanceString = "*";
public void Print(string threadMethodParam)
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine(string.Format("ThreadID: {0} {1} {2}",
Thread.CurrentThread.ManagedThreadId, threadMethodParam, instanceString));
Thread.Sleep(10);
}
}
}
class Program
{
static void Main(string[] args)
{
ShareDataInstanceVariable threadTest = new ShareDataInstanceVariable();
//Thread has separate call stack
Thread newThread = new Thread(() => threadTest.Print("+"));
newThread.Start();
//Main thread
threadTest.Print("-");
Console.ReadLine();
}
}
//Output
ThreadID: 10 - *
ThreadID: 11 + *
ThreadID: 10 - *
ThreadID: 11 + *
ThreadID: 11 + *
ThreadID: 10 - *