我一直在寻找互联网一段时间,但找不到任何符合我确切问题的东西。如果有人能够简洁地解释这一点,我将不胜感激。
基本上我想从我的客户端(Windows App)调用WCF Web服务,此服务将执行更新。但是,我希望该服务能够“回调”到客户端,因此用户可以通过可视化进度条查看正在进行的操作。可以这样做吗?
我已经看过全双工WCF服务的想法,其中有回调,并试图编写一些代码,但实际上并没有真正让这些回调触发,我大致知道wsDualHttpBinding与之间的困难。 netTcpBinding但无法真正得到工作。
目前我的测试是在同一个框中运行,即Windows应用程序和WCF服务(运行http://localhost:58781/)。我知道一旦这些转移到生产环境,我可能会遇到更多问题,所以我希望现在考虑这些问题。
非常感谢任何帮助。
答案 0 :(得分:2)
这是一个使用自托管服务和客户端的准系统示例。
<强>合同强>
[ServiceContract(CallbackContract = typeof(IService1Callback), SessionMode=SessionMode.Required)]
public interface IService1
{
[OperationContract]
void Process(string what);
}
public interface IService1Callback
{
[OperationContract]
void Progress(string what, decimal percentDone);
}
服务器强>
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
public class Service1 : IService1
{
public void Process(string what)
{
Console.WriteLine("I'm processing {0}", what);
for (int i = 0; i < 10; i++)
{
OperationContext.Current.GetCallbackChannel<IService1Callback>().Progress(what, (i+1)*0.1M);
}
}
}
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost( typeof(Service1), new Uri[] { new Uri("net.tcp://localhost:6789") }))
{
host.AddServiceEndpoint(typeof(IService1), new NetTcpBinding(SecurityMode.None), "Service1");
host.Open();
Console.ReadLine();
host.Close();
}
}
}
<强>客户端强>
public class CallbackHandler : IService1Callback
{
public void Progress(string what, decimal percentDone)
{
Console.WriteLine("Have done {0:0%} of {1}", percentDone, what);
}
}
class Program
{
static void Main(string[] args)
{
// Setup the client
var callbacks = new CallbackHandler();
var endpoint = new EndpointAddress(new Uri("net.tcp://localhost:6789/Service1"));
using (var factory = new DuplexChannelFactory<IService1>(callbacks, new NetTcpBinding(SecurityMode.None), endpoint))
{
var client = factory.CreateChannel();
client.Process("JOB1");
Console.ReadLine();
factory.Close();
}
}
}
这使用net.tcp上的双工通道,服务器触发通信,通知客户端进度更新。
客户端将显示:
Have done 10% of JOB1
Have done 20% of JOB1
Have done 30% of JOB1
Have done 40% of JOB1
Have done 50% of JOB1
Have done 60% of JOB1
Have done 70% of JOB1
Have done 80% of JOB1
Have done 90% of JOB1
Have done 100% of JOB1