Prefer Futures to Baked-In "Async APIs"一文介绍了如何使用语言的并行API通过异步来实现这点。普通同步性质的方法如下:
RetType DoSomething( InParameters ins, OutParameters outs ); <p class="indent">
result = DoSomething( this, that, outTheOther ); OtherWork(); <p class="indent">
IAsyncResult BeginDoSomething( InParameters ins ); <p class="indent">
RetType EndDoSomething( IAsyncResult asyncResult,//上一接口计算的结果 OutParameters outs ); <p class="indent">
IAsyncResult ar = BeginDoSomething( this, that ); result = DoSomething( this, that, outTheOther ); //在DoSomething运行同时,执行OtherWork OtherWork(); //将上面两个融合Join, ar.AsyncWaitHandle.WaitOne();//必要时需要等待 result = EndDoSomething( ar, outtheOther ); <p class="indent">
//第一步 asynchronous call future<int> result = async( ()=<{ return CallSomeFunc(x,y,z); } ); //第二步 code here runs concurrently with CallSomeFunc //同时运行其他事情 //第三步 use result when it's ready (this might block) //在这里使用异步运行dosomething的结果 DoSomethingWith( result.value() ); <p class="indent">
private void asynExecMessageListener(final DomainMessage message) { FutureTask futureTask = new FutureTask(new Callable<Boolean>() { public Boolean call() throws Exception { try { message.getMessageListener().action(message); } catch (Exception e) { .... return true; } }); message.addFutureTask(futureTask);//运行futuretask executor.execute(futureTask);//相当于pool.run } <p class="indent">
[该贴被admin于2010-01-20 09:22修改过]
//根据部门Id统计部门下所有员工的数量 int GetEmployeeCount(int departmentId) { Thread.Sleep(1000); return 100; } //输出员工数量 void OutputEmployeeCount(int employeeCount) { Assert.IsTrue(employeeCount == 100); } Func<int, int> task = GetEmployeeCount; int departmentId = 1; task.BeginInvoke(departmentId, future => OutputEmployeeCount(task.EndInvoke(future)), null); <p class="indent">