(12条消息) C#中关于线程启动运行带多参数方法的操作

不带参数的用ThreadStart委托指向要执行的方法,将ThreadStart对象传入Thread的构造函数

  1. public void Test()
  2. {
  3. Console.WriteLine("Test");
  4. }
  5. ThreadStart s = new ThreadStart(Test);
  6. Thread th = new Thread(s);
  7. th.Start();

带参数的可以用ParmeterizedThreadStart委托

  1. ParameterizedThreadStart s = new ParameterizedThreadStart(TestThreadParsms);
  2. Thread t = new Thread(s);
  3. t.IsBackground = true;
  4. t.Start("你好啊");
  5. public void TestThreadParsms(object obj)
  6. {
  7. Console.WriteLine(obj.ToString());
  8. }

如果遇到要传入多个参数的方法的时候,可以有2中解决方式,代码如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;

  6. namespace C1
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. #region 利用ParameterizedThreadStart委托传入object数组,将参数放到数据中传入线程
  13. //ParameterizedThreadStart s = new ParameterizedThreadStart(Test1);
  14. //Thread t = new Thread(s);
  15. //t.IsBackground = true;
  16. //t.Start(new object[]{"你好啊",2});
  17. #endregion
  18. #region 利用新建类中写实现目的功能的方法,转换成利用ThreadStart委托
  19. MyClass my = new MyClass("你好啊", 2);
  20. ThreadStart s = new ThreadStart(my.Test1);
  21. Thread t = new Thread(s);
  22. t.Start();
  23. #endregion
  24. Console.ReadKey();

  25. }
  26. public static void Test1(object obj)
  27. {

  28. Console.WriteLine(((object[])obj)[0].ToString());
  29. Console.WriteLine((Convert.ToInt32(((object[])obj)[1])*32).ToString());
  30. }
  31. }
  32. class MyClass
  33. {
  34. private string str;
  35. public string Str
  36. {
  37. get { return str; }
  38. set { str = value; }
  39. }

  40. private int num;
  41. public int Num
  42. {
  43. get { return num; }
  44. set { num = value; }
  45. }

  46. public MyClass(string str,int num)
  47. {
  48. this.str = str;
  49. this.num = num;
  50. }

  51. public void Test1()
  52. {

  53. Console.WriteLine(this.str);
  54. Console.WriteLine((this.num*32).ToString());
  55. }
  56. }
  57. }

(0)

相关推荐