C# 带参多线程操作

启动时创建线程并传递数据

创建线程

新建 Thread 对象会新建托管线程。 Thread 类包含需要使用 ThreadStart 委托或 ParameterizedThreadStart 委托的构造函数;委托包装在调用 Start 方法时由新线程调用的方法。 多次调用 Start 会导致 ThreadStateException 抛出。
线程一旦启动,就无需保留对 Thread 对象的引用。 线程可以继续执行到线程过程结束。
下面的代码示例新建两个线程,以对另一个对象调用实例和静态方法:

using System;
using System.Threading;

public class ServerClass
{
    // The method that will be called when the thread is started.
    public void InstanceMethod()
    {
        Console.WriteLine(
            "ServerClass.InstanceMethod is running on another thread.");

        // Pause for a moment to provide a delay to make
        // threads more apparent.
        Thread.Sleep(3000);
        Console.WriteLine(
            "The instance method called by the worker thread has ended.");
    }

    public static void StaticMethod()
    {
        Console.WriteLine(
            "ServerClass.StaticMethod is running on another thread.");

        // Pause for a moment to provide a delay to make
        // threads more apparent.
        Thread.Sleep(5000);
        Console.WriteLine(
            "The static method called by the worker thread has ended.");
    }
}

public class Simple
{
    public static void Main()
    {
        ServerClass serverObject = new ServerClass();

        // Create the thread object, passing in the
        // serverObject.InstanceMethod method using a
        // ThreadStart delegate.
        Thread InstanceCaller = new Thread(
            new ThreadStart(serverObject.InstanceMethod));

        // Start the thread.
        InstanceCaller.Start();

        Console.WriteLine("The Main() thread calls this after "
            + "starting the new InstanceCaller thread.");

        // Create the thread object, passing in the
        // serverObject.StaticMethod method using a
        // ThreadStart delegate.
        Thread StaticCaller = new Thread(
            new ThreadStart(ServerClass.StaticMethod));

        // Start the thread.
        StaticCaller.Start();

        Console.WriteLine("The Main() thread calls this after "
            + "starting the new StaticCaller thread.");
    }
}
// The example displays the output like the following:
//    The Main() thread calls this after starting the new InstanceCaller thread.
//    The Main() thread calls this after starting the new StaticCaller thread.
//    ServerClass.StaticMethod is running on another thread.
//    ServerClass.InstanceMethod is running on another thread.
//    The instance method called by the worker thread has ended.
//    The static method called by the worker thread has ended.

将数据传递到线程

将线程过程和数据封装到帮助程序类中,并使用 ThreadStart 委托执行线程过程。 下面的示例演示这一方法:

using System;
using System.Threading;

// The ThreadWithState class contains the information needed for
// a task, and the method that executes the task.
//
public class ThreadWithState
{
    // State information used in the task.
    private string boilerplate;
    private int numberValue;

    // The constructor obtains the state information.
    public ThreadWithState(string text, int number)
    {
        boilerplate = text;
        numberValue = number;
    }

    // The thread procedure performs the task, such as formatting
    // and printing a document.
    public void ThreadProc()
    {
        Console.WriteLine(boilerplate, numberValue);
    }
}

// Entry point for the example.
//
public class Example
{
    public static void Main()
    {
        // Supply the state information required by the task.
        ThreadWithState tws = new ThreadWithState(
            "This report displays the number {0}.", 42);

        // Create a thread to execute the task, and then
        // start the thread.
        Thread t = new Thread(new ThreadStart(tws.ThreadProc));
        t.Start();
        Console.WriteLine("Main thread does some work, then waits.");
        t.Join();
        Console.WriteLine(
            "Independent task has completed; main thread ends.");
    }
}
// The example displays the following output:
//       Main thread does some work, then waits.
//       This report displays the number 42.
//       Independent task has completed; main thread ends.

多线程操作

下面的例程演示的是所有子线程并发执行,并且所有子线程都执行完任务后,主线程才能接着执行后面的任务。其中class Decode创建并启动多个子线程,子线程要执行的任务由class WriteDataToList定义

public class Decode
{
     List<Thread> threads = new List<Thread>();
     for (int threadCount = 0; threadCount < threadNum; threadCount++)
     {
        WriteDataToList threadId = new WriteDataToList(decodeData, threadCount,dotNum,threadNum ,decodeLength, currentLocation);
        threads.Add(new Thread(new ThreadStart(threadId.ThreadProc)));
     }
     foreach (var thread in threads)
     {
        thread.Start();
     }
     //等待所有子线程结束后再运行主线程
     foreach (var thread in threads)
     {
         thread.Join();                    
     }
}
public class WriteDataToList
{
	int currentLocation;
	private byte[] decodeData;
	private int threadId;
	
	public WriteDataToList(byte[] buffer, int id, int dotNumber,int threadNumber ,int dataLength,int location)
    {
        currentLocation = location;
        decodeData = buffer;
        threadId = id;
    }
    public void ThreadProc()
    {
    	//do something
    	Debug.Log(threadId);
    }
}

下面的例子演示的是每次只允许一个子线程执行任务,其他线程等待。这样做的目的是为了方便多线程的调试:

class Decode
{
     List<Thread> threads = new List<Thread>();
     for (int threadCount = 0; threadCount < threadNum; threadCount++)
     {
        WriteDataToList threadId = new WriteDataToList(decodeData, threadCount,dotNum,threadNum ,decodeLength, currentLocation);
        threads.Add(new Thread(new ThreadStart(threadId.ThreadProc)));
     }
     //每次只允许一个子线程参与执行
     foreach (var thread in threads)
     {
        thread.Start();
        thread.Join(); 
     }
}

参考链接

https://docs.microsoft.com/zh-cn/dotnet/standard/threading/creating-threads-and-passing-data-at-start-time
http://www.cocoachina.com/articles/103071

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值