C#调用函数启动线程
时间: 2023-07-01 17:06:38 浏览: 66
在C#中启动线程可以使用Thread类的Start方法。以下是一个示例代码:
```csharp
using System;
using System.Threading;
class Program
{
static void Main()
{
Thread t = new Thread(MyThreadFunction);
t.Start();
Console.WriteLine("Main thread exits.");
}
static void MyThreadFunction()
{
Console.WriteLine("Thread started.");
// 在这里编写线程执行的代码
Console.WriteLine("Thread ended.");
}
}
```
在上面的代码中,我们创建了一个名为t的新线程,并调用Start方法启动它。线程的主体是MyThreadFunction方法,我们在这个方法中编写要在新线程中执行的代码。
需要注意的是,在启动线程之后,主线程不会等待新线程完成,而是继续执行。如果需要等待新线程完成,可以使用Thread.Join方法。例如:
```csharp
Thread t = new Thread(MyThreadFunction);
t.Start();
t.Join(); // 等待新线程完成
Console.WriteLine("Main thread exits.");
```