c#中创建新的线程执行一个带参数的有返回值的方法
时间: 2023-11-20 21:14:52 浏览: 51
可以使用Thread类的构造函数创建新的线程,并使用ParameterizedThreadStart委托指定要执行的带参数方法,最后使用Thread类的Start方法启动线程。另外,可以使用Func委托来指定要执行的有返回值的方法。以下是示例代码:
```
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
// 创建新线程并启动
Thread thread = new Thread(new ParameterizedThreadStart(SomeMethodWithParameter));
thread.Start("Hello, World!");
// 等待新线程完成
thread.Join();
Console.ReadKey();
}
static void SomeMethodWithParameter(object parameter)
{
Console.WriteLine("Parameter: " + parameter);
}
static string SomeMethodWithReturnValue(string parameter)
{
return "Hello, " + parameter;
}
}
```
若要执行有返回值的方法,可以使用Func委托来指定要执行的方法,示例代码如下:
```
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
// 创建新线程并启动
string parameter = "World";
Thread thread = new Thread(() =>
{
string result = SomeMethodWithReturnValue(parameter);
Console.WriteLine(result);
});
thread.Start();
// 等待新线程完成
thread.Join();
Console.ReadKey();
}
static string SomeMethodWithReturnValue(string parameter)
{
return "Hello, " + parameter;
}
}
```
注意:在使用Func委托时,需要使用lambda表达式或匿名方法来指定要执行的方法。