gpt4 book ai didi

wcf - 如何检测等待的异步 wcf 调用?

转载 作者:行者123 更新时间:2023-12-03 03:44:00 25 4
gpt4 key购买 nike

我从 silverlight 应用程序调用 WCF 服务。我正在异步执行此操作,并且在进行异步后不会阻止执行。调用(这意味着我没有使用等待加入机制 frm this page )。我不希望流量被阻塞。

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

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

但是,这是大量的样板代码,并且随着整个客户端代码中进行的调用越来越多,这只会变得更加困惑。

那么,wcf 服务客户端引用代码是否公开了任何方法或属性,可用于在任何异步 wcf 服务调用进入等待状态时触发关闭事件,同样,在所有异步 wcf 服务调用进入等待状态时触发关闭事件服务调用完成吗?

最佳答案

生成的客户端引用类上没有可用于标识当前正在进行的对 Silverlight WCF 服务方法的异步调用的属性或事件。不过,您可以使用一个简单的 bool 变量自己记录这一点,或者使用您提到的在这种情况下要避免的阻塞线程同步。

以下是如何使用 Silverlight ProgressBar control 执行您想要的操作的示例指示等待/正在处理对非常简单的 Silverlight Web 服务的调用:

页面.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>

Page.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 后将 IsInminated 设置为 true 会使进度条不确定地显示动画,如下所示:

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

由于对 OnClientDoWorkCompleted 的回调发生在 UI 线程上,因此可以在方法主体中将 IsInminated 属性的值更改回 false;当工作/等待现已完成时,这会再次导致无动画的空白进度条。

下面是 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 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/568439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com