在Linux和Windows Forms應用程序中實現多線程的方法略有不同
在Linux上使用C#和Mono時,可以使用System.Threading
命名空間中的Thread
類或Task
類來實現多線程。以下是一個簡單的示例:
using System;
using System.Threading;
namespace MultiThreadingExample
{
class Program
{
static void Main(string[] args)
{
// 創建一個新線程并執行方法
Thread newThread = new Thread(DoWork);
newThread.Start();
// 在主線程中執行其他操作
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Main thread: " + i);
Thread.Sleep(1000);
}
}
static void DoWork()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Worker thread: " + i);
Thread.Sleep(1000);
}
}
}
}
或者使用Task
類:
using System;
using System.Threading.Tasks;
namespace MultiThreadingExample
{
class Program
{
static void Main(string[] args)
{
// 創建一個新任務并執行方法
Task task = Task.Run(DoWork);
// 在主線程中執行其他操作
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Main thread: " + i);
Thread.Sleep(1000);
}
// 等待任務完成
task.Wait();
}
static void DoWork()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Worker thread: " + i);
Thread.Sleep(1000);
}
}
}
}
在Windows Forms應用程序中,可以使用System.Threading
命名空間中的Thread
類或Task
類來實現多線程。以下是一個簡單的示例:
使用Thread
類:
using System;
using System.Threading;
using System.Windows.Forms;
namespace MultiThreadingExample
{
public class MyForm : Form
{
private Button button;
public MyForm()
{
button = new Button();
button.Text = "Start";
button.Click += Button_Click;
this.Controls.Add(button);
}
private void Button_Click(object sender, EventArgs e)
{
// 創建一個新線程并執行方法
Thread newThread = new Thread(DoWork);
newThread.Start();
}
static void DoWork()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Worker thread: " + i);
Thread.Sleep(1000);
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}
}
或者使用Task
類:
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MultiThreadingExample
{
public class MyForm : Form
{
private Button button;
public MyForm()
{
button = new Button();
button.Text = "Start";
button.Click += Button_Click;
this.Controls.Add(button);
}
private void Button_Click(object sender, EventArgs e)
{
// 創建一個新任務并執行方法
Task task = Task.Run(DoWork);
}
static void DoWork()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Worker thread: " + i);
Thread.Sleep(1000);
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}
}
在這兩個示例中,我們創建了一個簡單的Windows Forms應用程序,其中包含一個按鈕。當用戶單擊按鈕時,將創建一個新線程(或任務)并執行DoWork
方法。在DoWork
方法中,我們簡單地打印一些消息并暫停一秒鐘。請注意,這些示例適用于C#和Mono在Linux上的運行。