我有兴趣在解决方案中找到处理Silverlight异步调用链接的空白。请让我知道,如果你发现解决方案中的差距/问题。或者,如果有其他方法/模式来解决问题,请指出我的正确方向。异步调用跟踪
代码没有编译或测试
问题
我们有一个要求,做一些动作异步调用的一堆完成后。
例如,一旦服务调用完成,就将默认值分配给UI控件。
void Fun()
{
Servicecall1();
Servicecall2();
//Make sure the following is executed only after the previous async calls are finished.
AssignDefaultValues();
}
解决方案
的一种方式做,这是链接服务,通过调用回调。不过,我只是想知道它是如何通过像下面这样的特殊异步执行跟踪类的对象来实现它。
class SomeClass
{
AsyncMehodCallWatcher _methodcallwatcher = new AsyncMehodCallWatcher();
void fun()
{
_methodcallwatcher.AsyncMethodStartMultipleCall(() =>
{
//this function will be called automatically after the following service calls
AssignDefaultValues();
}, 2);
Servicecall1();
Servicecall2();
}
void Servicecall1()
{
serviceclient.DoSomething(DoSomethingcallback);
}
void DoSomethingcallback(object sender, GetCompletedEventArgs arg)
{
_methodcallwatcher.AsyncCallCompleted();
}
void Servicecall2()
{
serviceclient.DoSomething(DoSomething2callback);
}
void DoSomething2callback(object sender, GetCompletedEventArgs arg)
{
_methodcallwatcher.AsyncCallCompleted();
}
}
任何人谁需要调用Servicecall1(),或Servicecall2()应该调用AsyncMethodPreCall(空)。
这里是所提出的实现AsyncMehodCallWatcher
public class AsyncMehodCallWatcher
{
private int _counter = 0;
public AsyncMehodCallWatcher()
{
}
public void AsyncMethodPreCall()
{
AsyncMethodPreCall(null);
}
Action _callcompletedaction = null;
public void AsyncMethodStartMultipleCall(Action action, int numofcalls)
{
if (action != null)
{
if (_callcompletedaction != null)
{
throw new InvalidOperationException(LocalString.AsyncMehodCallWatcherErrorAsyncCalls);
}
_callcompletedaction = action;
_counter = numofcalls;
}
}
public void AsyncMethodPreCall(Action action)
{
if (action != null)
{
if (_callcompletedaction != null)
{
throw new InvalidOperationException(LocalString.AsyncMehodCallWatcherErrorAsyncCalls);
}
_callcompletedaction = action;
}
_counter++;
}
public void AsyncCallCompleted()
{
_counter--;
if (_counter < 0)
{
throw new InvalidOperationException(LocalString.AsyncMehodCallWatcherErrorAsyncCalls);
}
if (_counter == 0)
{
if (_callcompletedaction != null)
{
_callcompletedaction();
_callcompletedaction = null;
}
}
}
}
问题是什么 – Sajeetharan
对于所提到的问题,提出的解决方案是可接受的还是其他任何方式? – Jimmy
您针对Silverlight
Noseratio