C# 线程的创建(转)

1、无参数线程的创建

1

2

3

4

5

6

Thread thread = new Thread(new ThreadStart(getpic));

thread.Start();

private void showmessage()

{

Console.WriteLine("hello world");

}

2、带一个参数的线程

使用ParameterizedThreadStart,调用 System.Threading.Thread.Start(System.Object) 重载方法时将包含数据的对象传递给线程。

注意传递的参数只能是object类型,不过可以进行强制类型转换。

1

2

3

4

5

6

7

8

Thread thread = new Thread(new ParameterizedThreadStart(showmessage));

string o = "hello";

thread.Start((object)o);

private static void showmessage(object message)

{

string temp = (string)message;

Console.WriteLine(message);

}

3、带两个及以上参数的线程

这时候可以将线程执行的方法和参数都封装到一个类里边,通过实例化该类,方法就可以调用属性来尽享传递参数。

例如如下程序,想传入两个string变量,然后打印输出。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

public class ThreadTest

{

private string str1;

private string str2;

public ThreadTest(string a, string b)

{

str1 = a;

str2 = b;

}

public void ThreadProc()

{

Console.WriteLine(str1 + str2);

}

}

public class Example {

public static void Main()

{

ThreadTest tt = new ThreadTest("hello ", "world");

Thread thread = new Thread(new ThreadStart(tt.ThreadProc));

thread.Start();

}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值