3

我从我的Silverlight应用程序调用WCF服务。 我正在异步执行此操作,并且在进行异步操作后,我没有阻止执行。调用(这意味着,我不使用等待连接机制frm this page)。我不希望流量被阻止。如何检测等待异步wcf调用?

但是,我想检测到WCF调用已进入等待状态,以便我可以在UI上显示一个忙图标 - 一种可视通信,指示事件发生在UI后面。

我可以更改我的代码,以便我可以开始动画繁忙图标,并在异步调用完成时停止该动画。

但是,这是很多bolierplate代码,并且随着更多的客户端代码被调用,这只会变得更加混乱。

那么,是否有任何方法或财产公开的wcf服务客户端引用代码可用于触发事件时,任何异步wcf服务调用进入等待状态,同样,触发事件时,所有异步wcf服务电话完成?

+0

我使用的是单包装通过自动生成的wcf客户端引用,所以我总是使用wcf客户端的同一个实例。我的app.xaml.cs文件中有一个静态属性,在整个应用程序中公开这个单例。 – 2009-02-20 06:09:51

回答

4

生成的客户端引用类没有属性或事件可用于识别对Silverlight WCF服务的方法的异步调用是当前正在进行。你可以使用一个简单的布尔变量来记录它,或者使用你提到的你想避免的阻塞线程同步。

这里有一个如何做你想要使用Silverlight ProgressBar control什么指示等待/通话中工作,一个非常简单的Silverlight Web服务的例子:

Page.xaml:

<UserControl x:Class="SilverlightApplication1.Page" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="100"> 

    <StackPanel x:Name="LayoutRoot" Background="White"> 
     <Button x:Name="ButtonDoWork" Content="Do Work" 
       Click="ButtonDoWork_Click" 
       Height="32" Width="100" Margin="0,20,0,0" /> 
     <ProgressBar x:Name="ProgressBarWorking" 
        Height="10" Width="200" Margin="0,20,0,0" /> 
    </StackPanel> 
</UserControl> 

页。 xaml.cs:

using System.ComponentModel; 
using System.Windows; 
using System.Windows.Controls; 
using SilverlightApplication1.ServiceReference1; 

namespace SilverlightApplication1 
{ 
    public partial class Page : UserControl 
    { 
     public bool IsWorking 
     { 
      get { return ProgressBarWorking.IsIndeterminate; } 
      set { ProgressBarWorking.IsIndeterminate = value; } 
     } 

     public Page() 
     { 
      InitializeComponent(); 
     } 

     private void ButtonDoWork_Click(object sender, RoutedEventArgs e) 
     { 
      Service1Client client = new Service1Client(); 
      client.DoWorkCompleted += OnClientDoWorkCompleted; 
      client.DoWorkAsync(); 

      this.IsWorking = true; 
     } 

     private void OnClientDoWorkCompleted(object sender, AsyncCompletedEventArgs e) 
     { 
      this.IsWorking = false; 
     } 
    } 
} 

异步调用DoWork的后设置IsIndeterminate为true,使进度条动画不定是这样的:

alt text http://www.freeimagehosting.net/uploads/89620987f0.png

因为回调OnClientDoWorkCompleted发生在UI线程它的优良改变IsIndeterminate属性的值回假方法主体;当工作/等待现在完成时,这会导致一个非动画空白的ProgressBar。

下面是Web服务和上面的代码调用异步的DoWork的方法的代码,它的作用是在5秒钟内睡觉模拟一些长时间运行的任务:

using System; 
using System.ServiceModel; 
using System.ServiceModel.Activation; 
using System.Threading; 

namespace SilverlightApplication1.Web 
{ 
    [ServiceContract(Namespace = "")] 
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
    public class Service1 
    { 
     [OperationContract] 
     public void DoWork() 
     { 
      Thread.Sleep(TimeSpan.FromSeconds(5.0)); 
      return; 
     } 
    } 
} 
+0

谢谢,我一定会试试这个。 我直到我将需要添加某种同步(锁定)围绕IsWorking变量,并使其成为一个int。这是因为会有并行的异步请求,并且动画应该继续直到所有的调用完成。 – 2009-02-20 16:23:46