zoukankan      html  css  js  c++  java
  • C#多线程编程 向线程传送数据

    向线程传送数据有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); 
            }
        }
    }
    
  • 相关阅读:
    牢骚与javascript中的this
    Vim 命令整理
    跟我一起写 Makefile
    Scikit-Learn模块学习笔记——数据预处理模块preprocessing
    Scikit-Learn模块学习笔记——数据集模块datasets
    Markdown 完全指南
    Shell命令行操作
    init_ir_技术实现篇
    ch2 创建和销毁对象
    ch6 影响 MySQLServer 性能的相关因素
  • 原文地址:https://www.cnblogs.com/herbert/p/1765352.html
Copyright © 2011-2022 走看看