在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");
}
}
}
|
版权声明:本文博客原创文章,博客,未经同意,不得转载。