生成的客户端引用类没有属性或事件可用于识别对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;
}
}
}
我使用的是单包装通过自动生成的wcf客户端引用,所以我总是使用wcf客户端的同一个实例。我的app.xaml.cs文件中有一个静态属性,在整个应用程序中公开这个单例。 – 2009-02-20 06:09:51