It's been a long time since I wrote a blog, the latest project doesn't have to write code. It's fine today. The method of parameter passing between threads, which is mainly used for parameter passing between two methods running on a different thread . Look directly at the code
1. Passing parameters directly between methods
voidDemoparam () {Console.WriteLine ("Demoparam:"+Thread.CurrentThread.ManagedThreadId); //thread t = new Thread (new Parameterizedthreadstart (Testparam)); //T.start ("majaing");ThreadPool.QueueUserWorkItem (NewWaitCallback (Testparam),"majaing"); } voidTestparam (Objectobj) {Console.WriteLine ("Demoparam:"+Thread.CurrentThread.ManagedThreadId); Console.WriteLine (obj. ToString ()); }
2. With static
//[ThreadStatic] Static stringNamekey; voiddemostatic () {Console.WriteLine ("Static:"+Thread.CurrentThread.ManagedThreadId); Namekey="Majiang"; ThreadPool.QueueUserWorkItem (NewWaitCallback (teststatic)); } voidTeststatic (Objectobj) {Console.WriteLine ("Static:"+Thread.CurrentThread.ManagedThreadId); Console.WriteLine (Namekey); }
3. With the AppDomain
voidDemoappdomain () {Console.WriteLine ("AppDomain:"+Thread.CurrentThread.ManagedThreadId); AppDomain.CurrentDomain.SetData ("name","Majiang"); ThreadPool.QueueUserWorkItem (NewWaitCallback (Testappdomain)); } voidTestappdomain (Objectobj) {Console.WriteLine ("AppDomain:"+Thread.CurrentThread.ManagedThreadId); varA = AppDomain.CurrentDomain.GetData ("name"); Console.WriteLine (a); }
4. With CallContext
voidDemocallcontext () {Console.WriteLine ("CallContext"+Thread.CurrentThread.ManagedThreadId); //Executioncontext.suppressflow ();Callcontext.logicalsetdata ("name","Majiang"); ThreadPool.QueueUserWorkItem (NewWaitCallback (Testcallcontext)); } voidTestcallcontext (Objectobj) {Console.WriteLine ("CallContext"+Thread.CurrentThread.ManagedThreadId); varA = Callcontext.logicalgetdata ("name"); Console.WriteLine (a); }
Note the notes inside.
How parameters are passed between different threads in the same application domain in C #