C # PASS Parameters to n methods of the thread,

Source: Internet
Author: User

C # PASS Parameters to n methods of the thread,

[Transfer] http://kb.cnblogs.com/a/888688/

The topic in this article is about several methods for passing parameters to a thread.

First, we need to know what a thread is, when to use it, how to use it, and how to make better use of it to complete the work.
A thread is the minimum unit of a program executable fragment and the basic unit of the program at runtime. A process consists of at least one thread. Threads are generally used for parallel processing of wait events, such as waiting for network response, waiting for I/O communication, and background transaction processing. The thread usage is actually very simple. net Framework, you must first define a function to complete some work, and then instantiate a Thread object Thread thrd = new Thread (new ThreadStart (Thread function )); threadStart is a function delegate without parameters. Use thrd. Start () to Start the thread. Of course, this is just a simple example. In practice, there will be many problems to solve when using the thread, such as passing parameters to the thread, waiting for the thread to return, and how to synchronize the thread to access the same resource, how to prevent deadlocks and competition conditions, how to effectively use the thread pool, and how to provide thread efficiency. This article will only discuss how to pass parameters to the thread.

In the above example, we can see that the parameter instantiated by the thread is a function delegate without any parameters, so it proves that we cannot pass the parameter to the thread through such a delegate. So what should we do? Three methods can be implemented as far as I know: 1. use the thread implementation class to define the call parameters as attributes to operate the thread parameters. 2. input parameters are transmitted using the ParameterizedThreadStart delegate. 3. the thread pool is used for parameter input.

1. Create a thread implementation class. The biggest advantage of this method is that multiple return values can be returned through the thread.
Assume that the row, column, and character data that are printed are input through the main function in a printing thread, and the total number of printed characters is returned.
Class ThreadOutput
{
Int _ rowCount = 0;
Int _ colCount = 0;
Char _ char = '*';
Int _ ret = 0;

/** // <Summary>
/// Input parameters
/// </Summary>
Public int RowCount
{
Set {_ rowCount = value ;}
}

Public int ColCount
{
Set {_ colCount = value ;}
}

Public char Character
{
Set {_ char = value ;}
}

/** // <Summary>
/// Output parameters
/// </Summary>
Public int RetVal
{
Get {return _ ret ;}
}

Public void Output ()
{
For (int row = 0; row <_ rowCount; row ++)
{
For (int col = 0; col <_ colCount; col ++)
{
Console. Write ("{0}", _ char );
_ Ret ++;
}
Console. Write ("\ n ");
}
}


ThreadOutput to1 = new ThreadOutput ();
To1.RowCount = 10;
To1.ColCount = 20;

Thread thrd = new Thread (new ThreadStart (to1.Output ));
// Set it to the background thread, mainly because it does not affect the end of the main thread
Thrd. IsBackground = true;
Thrd. start (); note that because the thread implementation class transmits values through the attribute, thread synchronization is required in the attribute accessors; otherwise, the obtained values may be incorrect.

2. input parameters are transmitted using the ParameterizedThreadStart delegate.
The ParameterizedThreadStart delegation is only available in. Net2.0. This delegate is used to transmit an object parameter to the thread when the thread is started. This method is relatively simple to use, but there is a risk of inconsistent types because you need to convert the object type.

3. Use the thread pool to implement parameter input
What is a thread pool? The thread pool is a container provided by the system to store threads. The thread control after entering the thread pool is controlled by the system. The advantage of using the thread pool is that we don't need to think about what to do for the thread to have a lot of free time, which is suitable for conventional transaction processing. In. Net, the thread pool is a static class, so we need to call related functions through ThreadPool. The function used to add a thread to the thread pool is ThreadPool. QueueUserWorkItem (new WaitCallBack (), object obj ). This function has a WaitCallBack delegate, [ComVisibleAttribute (true)]
Public delegate void WaitCallback (Object state)
Through this delegate, we can also pass parameters to the thread.

In fact, there is another way to pass parameters to the thread, that is, through the callback function, but this method is essentially the same as the first way to pass parameters through class data members. So I will not elaborate on it!

For specific implementation, refer to the following source code:

The source code is as follows: (vs 2005 is compiled)
1 using System;
2 using System. Collections. Generic;
3 using System. Text;
4 using System. Threading;
5
6 namespace UsingThread
7 {
8 struct RowCol
9 {
10 public int row;
11 public int col;
12 };
13
14 class ThreadOutput
15 {
16 // create a wait time
17 static public ManualResetEvent prompt = new ManualResetEvent (false );
18
19 int _ rowCount = 0;
20 int _ colCount = 0;
21 char _ char = '*';
22 int _ ret = 0;
23
24/*** // <summary>
25 // input parameters
26 /// </summary>
27 public int RowCount
28 {
29 set {_ rowCount = value ;}
30}
31
32 public int ColCount
33 {
34 set {_ colCount = value ;}
35}
36
37 public char Character
38 {
39 set {_ char = value ;}
40}
41
42/*** // <summary>
43 // output parameters
44 /// </summary>
45 public int RetVal
46 {
47 get {return _ ret ;}
48}
49
50 public void Output ()
51 {
52 for (int row = 0; row <_ rowCount; row ++)
53 {
54 for (int col = 0; col <_ colCount; col ++)
55 {
56 Console. Write ("{0}", _ char );
57 _ ret ++;
58}
59 Console. Write ("\ n ");
60}
61 // activation event
62 prompt. Set ();
63}
64
65 public void Output (Object rc)
66 {
67 RowCol rowCol = (RowCol) rc;
68 for (int I = 0; I <rowCol. row; I ++)
69 {
70 for (int j = 0; j <rowCol. col; j ++)
71 Console. Write ("{0}", _ char );
72 Console. Write ("\ n ");
73}
74}
75}
76
77 class Program
78 {
79 static void Main (string [] args)
80 {
81 ThreadOutput to1 = new ThreadOutput ();
82 to1.RowCount = 10;
83 to1.ColCount = 20;
84
85 Thread thrd = new Thread (new ThreadStart (to1.Output ));
86 // set it to the background thread, mainly for the end of the main thread not affected
87 thrd. IsBackground = true;
88 thrd. Start ();
89
90 // create event wait
91 ThreadOutput. prompt. WaitOne ();
92
93 Console. WriteLine ("{0}", to1.RetVal );
94
95 ThreadOutput to2 = new ThreadOutput ();
96 to2.RowCount = 5;
97 to2.ColCount = 18;
98 to2.Character = '^ ';
99 Thread thrds = new Thread (new ThreadStart (to2.Output ));
100 thrds. IsBackground = true;
101 thrds. Start ();
102 thapsaradb for RDS. Join ();
103
104 Console. WriteLine ("{0}", to2.RetVal );
105
106 // another Implementation of passing parameters to the thread
107 RowCol rc = new RowCol ();
108 rc. row = 12;
109 rc. col = 13;
110 to1.Character = '@';
111 if (ThreadPool. QueueUserWorkItem (new WaitCallback (to1.Output), rc ))
112 Console. WriteLine ("Insert Pool is success! ");
113 else
114 Console. WriteLine ("Insert Pool is failed! ");
115 Thread. Sleep (1000 );
116
117
118 // use the new ThreadStart delegate to PASS Parameters
119 rc. col = 19;
120 to2.Character = '#';
121 Thread thrdt = new Thread (new ParameterizedThreadStart (to2.Output ));
122 thrdt. Start (rc );
123 thrdt. Join ();
124}
125
126}
127}
128

 


C language ^ how to use

A1 = 0x01; // 0000 0001
A2 = 0x00; // 0000 0000
A3 = 0x03; // 0000 0011
A4 = 0x02; // 0000 0010

B1 = a1 ^ a2; // 0000 0001
B2 = a1 ^ a3; // 0000 0010
B3 = a1 ^ a4; // 0000 0011

^ XOR operator. The bitwise value is 0 and the difference is 1. See the example above.

//
Examples of simple and practical problems:
====================================
======= A ======= B =========
There are two circuits on the top. The two switches are a and B respectively. The opening status is \ [1], and the closing status is/[0].
If both circuits are enabled or disabled.
If a turns on [1], B turns off [0], and circuit 1 Powers on
=====================
If a disables [0], B enables [1], and circuit 2 powers on.
====================================
In summary, the circuit fails in the and B states simultaneously [0]. When a and B are different, the power is charged [1].

C language ^ how to use

A1 = 0x01; // 0000 0001
A2 = 0x00; // 0000 0000
A3 = 0x03; // 0000 0011
A4 = 0x02; // 0000 0010

B1 = a1 ^ a2; // 0000 0001
B2 = a1 ^ a3; // 0000 0010
B3 = a1 ^ a4; // 0000 0011

^ XOR operator. The bitwise value is 0 and the difference is 1. See the example above.

//
Examples of simple and practical problems:
====================================
======= A ======= B =========
There are two circuits on the top. The two switches are a and B respectively. The opening status is \ [1], and the closing status is/[0].
If both circuits are enabled or disabled.
If a turns on [1], B turns off [0], and circuit 1 Powers on
=====================
If a disables [0], B enables [1], and circuit 2 powers on.
====================================
In summary, the circuit fails in the and B states simultaneously [0]. When a and B are different, the power is charged [1].

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.