[C#][VB.NET].NET 4.0 Barrier Class
Module Module1
Private sync As Barrier
Sub Main(ByVal args() As String)
sync = New Barrier(3)
Dim charlie = New Thread(Sub() DriveToBoston("Charlie", TimeSpan.FromSeconds(1)))
charlie.Start()
Dim mac = New Thread(Sub() DriveToBoston("Mac", TimeSpan.FromSeconds(2)))
mac.Start()
Dim dennis = New Thread(Sub() DriveToBoston("Dennis", TimeSpan.FromSeconds(3)))
dennis.Start()
charlie.Join()
mac.Join()
dennis.Join()
Console.ReadKey()
End Sub
Sub DriveToBoston(ByVal name As String, ByVal timeToGasStation As TimeSpan)
Console.WriteLine("[{0}] Leaving House", name)
' Perform some work
Thread.Sleep(timeToGasStation)
Console.WriteLine("[{0}] Arrived at Gas Station", name)
' Need to sync here
sync.SignalAndWait()
' Perform some more work
Console.WriteLine("[{0}] Leaving for Gas Station", name)
End Sub
End Module C# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading;
namespace BarrierDemo { class Program { static Barrier sync;
static void Main(string[] args)
{
sync = new Barrier(3);
var charlie = new Thread(() => DriveToBoston("Charlie", TimeSpan.FromSeconds(1))); charlie.Start();
var mac = new Thread(() => DriveToBoston("Mac", TimeSpan.FromSeconds(2))); mac.Start();
var dennis = new Thread(() => DriveToBoston("Dennis", TimeSpan.FromSeconds(3))); dennis.Start();
charlie.Join();
mac.Join();
dennis.Join();
Console.ReadKey();
}
static void DriveToBoston(string name, TimeSpan timeToGasStation)
{
Console.WriteLine("[{0}] Leaving House", name);
// Perform some work
Thread.Sleep(timeToGasStation);
Console.WriteLine("[{0}] Arrived at Gas Station", name);
// Need to sync here
sync.SignalAndWait();
// Perform some more work
Console.WriteLine("[{0}] Leaving for Gas Station", name);
}
}
} 運行結果 若是不使用Barrier去同步,這邊我們可以拿掉sync.SignalAndWait()再做一次運行,則三個人就會變成各自前往西雅圖喝咖啡了。 LinkMSDN - Barrier ClassStackOverFlow - Difference between Barrier in C# 4.0 and WaitHandle in C# 3.0?Managed World - An Intro to Barrier