How to transmit data between the main thread and sub-thread in C #
How to transmit data between the main thread and sub-thread in C #
Laoshuai
When creating a Thread in C #, there can be multiple methods, and how to transfer data between the main Thread and the sub-Thread is different in the effect of passing parameters for each creation method, one by one:
1. Create a Thread without Parameters
1234567891011121314151617181920212223 |
using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace ATest { class A { public static void Main() { Thread t = new Thread( new ThreadStart(A)); t.Start(); Console.Read(); } private static void A() { Console.WriteLine( "Parameter A is not included! " ); } } } |
The result shows "No parameter !"
2. Include a parameterCreate Thread
Because ParameterizedThreadStart requires that the parameter type be object, the type of the parameter defined in Method B must be object.
123456789101112131415161718192021222324 |
using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace BTest { class B { public static void Main() { Thread t = new Thread( new ParameterizedThreadStart(B)); t.Start( "B" ); Console.Read(); } private static void B( object obj) { Console.WriteLine( "With a parameter {0 }! " ,obj.ToString ()); } } } |
The result shows "with a parameter B !"
3. Multiple ParametersCreate Thread
Because Thread only provides the two constructors by default, if you need to pass multiple parameters, you can pass the parameters as class attributes to the Thread based on the second method.
1234567891011121314151617181920212223242526272829303132 |
Using System; using System. collections. generic; using System. text; using System. threading; namespace CTest {class C {public static void Main () {MyParam m = new MyParam (); m. x = 6; m. y = 9; Thread t = new Thread (new ThreadStart (m. test); t. start (); Console. read () ;}} class MyParam {public int x, y; public void Test () {Console. writeLine ("x = {0}, y = {1}", this. x, this. y );}}} |
The result shows "x = 6, y = 9"
4. Use the callback function to pass parameters to the main thread
Based on method 3, callback functions can be passed into the thread as a method of the class to facilitate thread callback.
1234567891011121314151617181920212223242526272829303132 |
Using System; using System. collections. generic; using System. text; using System. threading; namespace CTest {class C {public static void Main () {MyParam m = new MyParam (); m. x = 6; m. y = 9; m. callBack = ThreadCallBack; Thread t = new Thread (new ThreadStart (m. test); t. start (); Console. read ();}} Private void ThreadCallBack (string msg) {Console. WriteLine ("CallBack:" + msg);} private delegate void ThreadCallBackDelegate (string msg ); Class MyParam {public int x, y; public ThreadCallBackDelegate callBack; public void Test () {callBack ("x = 6, y = 9 ");}}} |
The result shows "CallBack: x = 6, y = 9"