在C#中主线程和子线程如何实现互相传递数据
老帅
一、不带参数创建Thread
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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(
"不带参数 A!"
);
}
}
}
|
结果显示“不带参数 A!”
由于ParameterizedThreadStart要求参数类型必须为object,所以定义的方法B形参类型必须为object。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
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(
"带一个参数 {0}!"
,obj.ToString ());
}
}
}
|
结果显示“带一个参数 B!”
由于Thread默认只提供了这两种构造函数,如果需要传递多个参数,可以基于第二种方法,将参数作为类的属性传给线程。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
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);
}
}
}
|
结果显示“x=6,y=9”
我们可以基于方法三,将回调函数作为类的一个方法传进线程,方便线程回调使用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
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");
}
}
}
|