向线程传送数据有2种方法:

  • 使用带参数的Threadstart方法
  • 创建一个定制类,把线程的方法定义为实例方法,这样就可以初始化实例的数据,之后启动线程。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

// 向线程传递数据
// Herbert
// 仅供个人学习使用

namespace ThreadDemo
{
    class Program
    {
        public struct Data
        {
            public string Message;
        }

        static void ThreadMainWithParameters(object o)
        {
            Data d = (Data)o;
            Console.WriteLine("Running in a thread, received {0}", d.Message);
        }

        static void Main(string[] args)
        {
            Data d = new Data();
            d.Message = "Info";

            Thread t2 = new Thread(ThreadMainWithParameters);
            t2.Start(d);

            MyThread obj = new MyThread("obj");
            Thread t3 = new Thread(obj.ThreadMain);
            t3.Start();
            Console.ReadKey();
        }
    }
}


MyThread类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ThreadDemo
{
    class MyThread
    {
        private string data;

        public MyThread(string data)
        {
            this.data = data;
        }

        public void ThreadMain()
        {
            Console.WriteLine("Running in a thread, data: {0}", data); 
        }
    }
}

相关文章:

  • 2022-02-15
  • 2021-10-25
  • 2021-07-10
  • 2021-10-10
  • 2022-03-04
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-23
  • 2021-08-24
  • 2021-08-20
  • 2021-09-07
相关资源
相似解决方案