下面是一個使用WaitHandle的一種可能的方法:
class Program
{
static void Main(string[] args)
{
Sender _sender = new Sender();
Receiver _receiver = new Receiver();
using (ManualResetEvent waitHandle = new ManualResetEvent(false))
{
// have to initialize this variable, otherwise the compiler complains when it is used later
int randomNumber = 0;
Thread thread1 = new Thread(new ThreadStart(() =>
{
randomNumber = _sender.GenerateNumber();
try
{
// now that we have the random number, signal the wait handle
waitHandle.Set();
}
catch (ObjectDisposedException)
{
// this exception will be thrown if the timeout elapses on the call to waitHandle.WaitOne
}
}));
// begin receiving the random number
thread1.Start();
// wait for the random number
if (waitHandle.WaitOne(/*optionally pass in a timeout value*/))
{
_receiver.TakeRandomNumber(randomNumber);
}
else
{
// signal was never received
// Note, this code will only execute if a timeout value is specified
System.Console.WriteLine("Timeout");
}
}
}
}
public class Sender
{
public int GenerateNumber()
{
Thread.Sleep(2000);
// http://xkcd.com/221/
int randomNumber = 4; // chosen by fair dice role
return randomNumber;
}
}
public class Receiver
{
public void TakeRandomNumber(int randomNumber)
{
// do something
System.Console.WriteLine("Received random number: {0}", randomNumber);
}
}
我只是想更新我的答案提供什麼,我認爲是使用在
Task<TResult>
類上面例子中的等價代碼。 NET S 4在Jon Skeet的回答中指出。信用歸功於他指出。謝謝,Jon。我還沒有理由使用該課程,並且當我看到使用這個課程有多容易時,我感到非常驚喜。
除了使用該課程獲得的性能優勢之外,使用Task<TResult>
類編寫等效代碼似乎更容易。例如,如下所示的主要方法上面可以改寫爲體:
Sender _sender = new Sender();
Receiver _receiver = new Receiver();
Task<int> getRandomNumber = Task.Factory.StartNew<int>(_sender.GenerateNumber);
// begin receiving the random number
getRandomNumber.Start();
// ... perform other tasks
// wait for up to 5 seconds for the getRandomNumber task to complete
if (getRandomNumber.Wait(5000))
{
_receiver.TakeRandomNumber(getRandomNumber.Result);
}
else
{
// the getRandomNumber task did not complete within the specified timeout
System.Console.WriteLine("Timeout");
}
如果你沒有必要指定任務超時,且內容無限期地等待它完成,然後你可以寫這使用更少的代碼:
Sender _sender = new Sender();
Receiver _receiver = new Receiver();
Task<int> getRandomNumber = Task.Factory.StartNew<int>(_sender.GenerateNumber);
// begin receiving the random number
getRandomNumber.Start();
// ... perform other tasks
// accessing the Result property implicitly waits for the task to complete
_receiver.TakeRandomNumber(getRandomNumber.Result);
兩個線程是否同時啓動? Receiver在等待發件人時正在做什麼?發件人在生成隨機數後會做些什麼? – cadrell0 2012-01-06 20:06:34
這是.NET 4嗎? – Yahia 2012-01-06 20:12:23
在主函數中,我將啓動這兩個線程,線程發送程序將工作,然後休眠3秒鐘。另外,我將開始接收數據的線程接收器的實例...basiclly線程將工作untui用戶按esc鍵...接收器將寫入收到的控制檯號碼。 – Avicena00 2012-01-06 20:12:43