C#多线程编程 - 向线程传送数据

本文介绍了两种向线程传递数据的方法:一是通过带有参数的ThreadStart委托创建自定义类,并将线程方法定义为实例方法;二是直接在构造函数中初始化数据成员。

向线程传送数据有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); 
        }
    }
}

转载于:https://www.cnblogs.com/herbert/archive/2010/06/25/1765352.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值