在C#中,處理單線程任務(wù)通常意味著在一個(gè)線程上執(zhí)行一系列操作,而不是并行執(zhí)行多個(gè)任務(wù)。這可以通過(guò)使用同步方法和阻塞調(diào)用來(lái)實(shí)現(xiàn)。下面是一些處理單線程任務(wù)的方法:
Thread.Sleep
方法暫停當(dāng)前線程:using System;
using System.Threading;
class Program
{
static void Main()
{
Console.WriteLine("Starting...");
Thread.Sleep(2000); // 暫停2秒
Console.WriteLine("Finished.");
}
}
BlockingCollection<T>
類提供了一個(gè)線程安全的集合,可以在生產(chǎn)者和消費(fèi)者之間傳輸數(shù)據(jù)。當(dāng)沒(méi)有數(shù)據(jù)可用時(shí),消費(fèi)者線程將阻塞,直到有數(shù)據(jù)可用。using System;
using System.Collections.Concurrent;
using System.Threading;
class Program
{
static void Main()
{
var blockingCollection = new BlockingCollection<int>();
var producer = new Thread(() =>
{
for (int i = 0; i < 5; i++)
{
blockingCollection.Add(i);
Thread.Sleep(500);
}
blockingCollection.CompleteAdding();
});
var consumer = new Thread(() =>
{
while (!blockingCollection.IsCompleted)
{
if (blockingCollection.TryTake(out int item))
{
Console.WriteLine($"Processed: {item}");
}
}
});
producer.Start();
consumer.Start();
producer.Join();
consumer.Join();
}
}
Monitor
或Mutex
進(jìn)行同步:這些類提供了同步原語(yǔ),允許您在代碼中創(chuàng)建臨界區(qū),確保在同一時(shí)間只有一個(gè)線程可以訪問(wèn)共享資源。using System;
using System.Threading;
class Program
{
private static readonly object _lockObject = new object();
private static int _counter = 0;
static void Main()
{
var thread1 = new Thread(IncrementCounter);
var thread2 = new Thread(IncrementCounter);
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
Console.WriteLine($"Counter: {_counter}");
}
static void IncrementCounter()
{
for (int i = 0; i < 1000; i++)
{
lock (_lockObject)
{
_counter++;
}
}
}
}
這些方法展示了如何在C#中處理單線程任務(wù)。請(qǐng)注意,這些示例僅用于演示目的,實(shí)際應(yīng)用程序可能需要更復(fù)雜的邏輯和錯(cuò)誤處理。