问题描述
C#/.NET应用程序编程开发中,我们可以new Thread()
来开启多线程,其中Thread
类可以接收ThreadStart
类型的参数,如下:
public static void Main()
{
var th = new Thread(new ThreadStart(() =>
{
Thread.Sleep(5000);
Console.WriteLine("sub thread task running...");
}))
{
IsBackground = true
};
th.Start();
Console.WriteLine("main thread...");
Console.ReadLine();
}
这里的ThreadStart
类型无法传递参数,如果我们要向ThreadStart
传递参数,应该如何实现呢?
方案一
使用ParameterizedThreadStart
类型作为Thread()
构造函数的参数,如下:
using System;
using System.Threading;
namespace ConsoleApp2
{
class Program
{
public static void Main()
{
var name = "Rector";
var th = new Thread(new ParameterizedThreadStart(DoWork))
{
IsBackground = true
};
th.Start(name);
Console.WriteLine("main thread run here...");
Console.ReadLine();
}
private static void DoWork(object name)
{
Thread.Sleep(2000);
Console.WriteLine("sub thread task running,parameter is {0}...", name);
}
}
}
方案二
使用ParameterizedThreadStart
传递参数时,只能传递一个object
的参数,如果要传递多个并且是强类型的参数时ParameterizedThreadStart
的方式无能为力了。
查看Thread
类的构造函数可知,Thread
有3个被重载的构造函数,我们可以使用ThreadStart
类型的lambda方式实现多参数传递,如下:
using System;
using System.Threading;
namespace ConsoleApp2
{
class Program
{
public static void Main()
{
var firstName = "Rector";
var lastName = "Liu";
var th = new Thread(() => DoWork(firstName, lastName))
{
IsBackground = true
};
th.Start();
Console.WriteLine("main thread...");
Console.ReadLine();
}
private static void DoWork(string firstName, string lastName)
{
Thread.Sleep(2000);
Console.WriteLine("sub thread task running,firstName is:{0}, lastName is:{1}...", firstName, lastName);
}
}
}
版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。
发表评论
登录用户才能发表评论, 请 登 录 或者 注册