Silverlight调用WCF双工通信问题
silverlight调用WCF服务时,服务端我做了一个timer,想定时将信息发送到SL端,但是这个timer好像根本没有工作。请大家帮忙看看。
WCF端服务契约代码:
[ServiceContract(CallbackContract = typeof(IDuplexClient))] public interface IDuplexService { [OperationContract] void Order(); } [ServiceContract] public interface IDuplexClient { [OperationContract(IsOneWay = true)] void Receive(string strMsg); }
public class OrderService : IDuplexService { IDuplexClient client; public void Order() { client = OperationContext.Current.GetCallbackChannel<IDuplexClient>(); Timer timer = new Timer(new TimerCallback(CallClient),this,500,1000); //timer不能定时执行方法 } private void CallClient(object o) { client.Receive(DateTime.Now + "调用一次!"); } }
public MainPage()
{
InitializeComponent();
this.Loaded+=new RoutedEventHandler(MainPage_Loaded);
}
private void MainPage_Loaded(object sender,RoutedEventArgs e)
{
EndpointAddress address = new EndpointAddress("http://localhost:1802/Service1.svc");
PollingDuplexHttpBinding binding = new PollingDuplexHttpBinding(PollingDuplexMode.MultipleMessagesPerPoll);
DuplexServiceClient proxy = new DuplexServiceClient(binding, address);
proxy.ReceiveReceived += new EventHandler <ReceiveReceivedEventArgs>(proxy_ReceiveReceived);
proxy.OrderAsync();
reply.Text = DateTime.Now + ":开始调用" + Environment.NewLine;
}
void proxy_ReceiveReceived(object sender, ReceiveReceivedEventArgs e)
{
if (e.Error == null)
{
reply.Text = e.strMsg;
}
}
最近才研究WCF中的双工问题,其实LZ的问题出现的原因很简单,
应该说是微软自己给出的例子就有问题,LZ应当该让主程序等待足够长的时间,让 timer 有时间运行完成,
微软给出的例子代码不是这样的么:
using (Timer timer = new Timer(new TimerCallback(CallClient), null, 5000, 5000)){ Thread.Sleep(8000);}
[解决办法]