Sharing Data between Threads
If threads do want to share data, they do so via a common reference. This can be a captured variable as we saw previously—but much more often it’s a field. Here’s an example:
Example
using System; using System.Threading; namespace ConsoleApplication1 { class Program { static void Main() { Introducer intro = new Introducer(); intro.Message = "Hello"; var t = new Thread(intro.Run); t.Start(); t.Join(); Console.WriteLine(intro.Reply); Console.Read(); } class Introducer { public string Message; public string Reply; public void Run() { Console.WriteLine(Message); Reply = "Hi right back!"; } } } }
Shared fields allow both for passing data to a new thread and for receiving data back from it later on. Moreover, they allow threads to communicate with each other as they’re running. Shared fields can be either instance or static.