c# 开新线程
在 C# 中,可以使用 Thread 类来创建一个新线程。以下是一个简单的例子:
using System;
using System.Threading;
public class Program {
public static void Main(string[] args) {
Thread t = new Thread(new ThreadStart(DoWork));
t.Start();
Console.WriteLine("Main thread is working...");
}
public static void DoWork() {
Console.WriteLine("New thread is working...");
}
}
在上面的代码中,我们使用 Thread 类创建了一个新线程,并在该线程中执行 DoWork 方法。在主线程中,我们启动了新线程并打印了一条消息。运行上面的代码,输出应该是这样的:
Main thread is working...
New thread is working...
注意,新线程执行 DoWork 方法时,它是在后台运行的,因此当主线程结束时,新线程也会随之结束。如果需要等待新线程执行完毕后再继续主线程的执行,可以使用 Thread.Join 方法来等待。例如:
using System;
using System.Threading;
public class Program {
public static void Main(string[] args) {
Thread t = new Thread(new ThreadStart(DoWork));
t.Start();
Console.WriteLine("Main thread is working...");
t.Join(); // 等待新线程执行完毕
Console.WriteLine("Main thread is done.");
}
public static void DoWork() {
Console.WriteLine("New thread is working...");
Thread.Sleep(5000); // 模拟耗时操作
Console.WriteLine("New thread is done.");
}
}
``
原文地址: https://www.cveoy.top/t/topic/dxZr 著作权归作者所有。请勿转载和采集!