Silverlight项目中访问WCF服务,都是通过异步线程模式调用的。在某些情况下我们的调用是需要同步进行,此时我们可以通过AutoResetEvent的线程等待特性实现Silverlight同步调用远端WCF服务。
线程通过对 AutoResetEvent 调用 WaitOne或WaitAll 方法来等待信号。如果 AutoResetEvent 为非终止状态,则线程会被阻止,并等待当前控制资源的线程通过调用 Set 方法来通知资源可用。调用 Set 向 AutoResetEvent 发信号以释放等待线程。
下边的例子,在页面加载时,要分三次调用WCF以获取数据,如果按原有的异步方式,则要在每个OnCompleted中调用下一个WCF访问,依次串联,这样很不方便,代码的可读性也大大下降。所以使用了AutoResetEvent对原有调用方式进行了修改,代码片段如下:
private System.Collections.ObjectModel.ObservableCollection<SilverService.ProspectTaskWork_Entity> workEntitys = null;
private System.Collections.ObjectModel.ObservableCollection<SilverService.ProspectTaskWork_Entity> attentionEntitys = null;
private System.Collections.ObjectModel.ObservableCollection<SilverService.FunctionRight_Entity> functionRights = null;
private AutoResetEvent EventAttention = null;
private AutoResetEvent EventFunction = null;
private AutoResetEvent[] EventArray = new AutoResetEvent[2];
private void Canvas_Loaded(object sender, RoutedEventArgs e)
{
EventAttention = new AutoResetEvent(false);
EventFunction = new AutoResetEvent(false);
EventArray[0] = EventAttention;
EventArray[1] = EventFunction;
//
SilverService.SilverLightClient client = new SilverService.SilverLightClient();
client.GetProspectTaskWorkListByUserIdCompleted += new EventHandler<SilverService.GetProspectTaskWorkListByUserIdCompletedEventArgs>(OnGetProspectTaskWorkListByUserIdCompleted);
client.GetProspectTaskWorkListByUserIdAsync(SilverService.WorkQueryType.ATTENTION_USERID, m_userId);
//
client.GetUserSystemRightsCompleted += new EventHandler<SilverService.GetUserSystemRightsCompletedEventArgs>(OnGetUserSystemRightsCompleted);
client.GetUserSystemRightsAsync(m_userId);
//
client.GetAllProspectTaskWorkCompleted += new EventHandler<SilverService.GetAllProspectTaskWorkCompletedEventArgs>(OnGetAllProspectTaskWorkCompleted);
client.GetAllProspectTaskWorkAsync();
}
void OnGetProspectTaskWorkListByUserIdCompleted(object sender, SilverService.GetProspectTaskWorkListByUserIdCompletedEventArgs e)
{
if (e.Error != null)
{
//错误处理
}
else
{
attentionEntitys = e.Result;
EventAttention.Set();
}
}
void OnGetUserSystemRightsCompleted(object sender, SilverService.GetUserSystemRightsCompletedEventArgs e)
{
(e.Error != null)
{
//错误处理
}
else
{
functionRights = e.Result;
EventFunction.Set();
}
}
private void OnGetAllProspectTaskWorkCompleted(object sender, SilverService.GetAllProspectTaskWorkCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message.ToString());
}
else
{
workEntitys = e.Result;
//线程等待
WaitHandle.WaitAll(EventArray);
//要做的操作.....
}
}