我想进行异步调用,然后处理第一个线程返回的值。我不想使用并行库。我可以使用.Net 2.0。我编写了以下程序,应该可以满足我的要求。但是有人可以指出是否有更好的解决方案吗?谢谢。
这是我的代码:
class Program
{
private static Worker _worker2;
private static Worker _worker3;
private static Worker _worker4;
private static Worker _worker1;
delegate void DoWorkDelegate(object param);
private static Worker _firstReturnedWorker = null;
private static object lockObject = new object();
public static void Main()
{
_worker1 = new Worker();
_worker2 = new Worker();
_worker3 = new Worker();
_worker4 = new Worker();
int i = 10;
DoWorkDelegate d1 = new DoWorkDelegate(_worker1.OnDoWork);
d1.BeginInvoke(1, OnThreadReturned, ++i);
DoWorkDelegate d2 = new DoWorkDelegate(_worker2.OnDoWork);
d2.BeginInvoke(2, OnThreadReturned, ++i);
DoWorkDelegate d3 = new DoWorkDelegate(_worker3.OnDoWork);
d3.BeginInvoke(3, OnThreadReturned, ++i);
DoWorkDelegate d4 = new DoWorkDelegate(_worker4.OnDoWork);
d4.BeginInvoke(4, OnThreadReturned, ++i);
Console.ReadKey();
}
private static void OnThreadReturned(IAsyncResult ar)
{
lock (lockObject)
{
if (_firstReturnedWorker == null)
{
var workerIdentifier = (int)ar.AsyncState;
switch (workerIdentifier)
{
case 11:
_firstReturnedWorker = _worker1;
break;
case 12:
_firstReturnedWorker = _worker2;
break;
case 13:
_firstReturnedWorker = _worker3;
break;
case 14:
_firstReturnedWorker = _worker4;
break;
}
}
else
{
return;
}
}
Console.WriteLine("First result received was {0}", _firstReturnedWorker.ReturnedValue);
}
}
public class Worker
{
public string ReturnedValue { get; private set; }
public void OnDoWork(object value)
{
ReturnedValue = Process((int)value);
}
private string Process(int numberToProcess)
{
return string.Format("{0} was processed by {1}", numberToProcess, Thread.CurrentThread.ManagedThreadId);
}
}