【问题标题】:WCF NamedPipes Service and WPF ClientWCF NamedPipes 服务和 WPF 客户端
【发布时间】:2013-09-18 12:23:13
【问题描述】:

我正在使用一个 Windows 服务,我也想在其中添加一个 GUI。我通过我的服务创建了一个 ServiceHost 对象并托管 WCF 命名管道服务,然后我使用控制台应用程序来使用 WCF 服务并从服务获取回调响应(从服务器发送到连接的客户端的消息),进行了概念验证。这很好用,我的控制台应用程序运行并从服务中获得响应,没有中断或延迟。

但是,当在我的 WPF GUI 应用程序中执行相同操作时,单击一个按钮然后调用 WCF 服务时,它会冻结整个 UI 线程,然后在几分钟后引发异常,然后使用消息回调更新 UI (服务器向连接的客户端发送消息)但是由于抛出异常,服务的任何返回值都会丢失。

我得到的两个异常消息是论文(最常见的是第一个):

1: 发送到net.pipe://localhost/PipeGUI的请求动作在指定的超时时间(00:00:59.9989999)内没有收到响应。分配给此操作的时间可能是较长超时的一部分。这可能是因为服务仍在处理操作,或者因为服务无法发送回复消息。提高操作的截止日期(通过输入通道/代理到图标文本通道并设置属性操作超时)并验证服务可以连接到客户端。

2:通讯对象System.ServiceModel.Channels.ServiceChannel,已被取消,不能用于通讯。

有人知道为什么会这样吗? 如有必要,我可以发布更多代码。

更新,添加代码供参考

public interface IClientCallback
{
    [OperationContract(IsOneWay = true)]
    void MessageRecived(string message);
}

[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IClientCallback))]
public interface IPipeServiceContract
{
    [OperationContract]
    string Hello();

    [OperationContract]
    void Message(string msg);

    [OperationContract(IsInitiating = true)]
    void Connect();

    [OperationContract(IsTerminating = true)]
    void Disconnect();
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, IncludeExceptionDetailInFaults = true, UseSynchronizationContext = false)]
public class PipeService : IPipeServiceContract
{
    List<IClientCallback> _clients = new List<IClientCallback>();

    public string Hello()
    {
        PublishMessage("Hello World.");
        return "Return from method!";
    }

    public void Connect()
    {
        _clients.Add(OperationContext.Current.GetCallbackChannel<IClientCallback>());
    }

    public void Disconnect()
    {
        IClientCallback callback = OperationContext.Current.GetCallbackChannel<IClientCallback>();
        _clients.Remove(callback);
    }

    void PublishMessage(string message)
    {
        for (int i = _clients.Count - 1; i > 0; i--)
        {
            try
            {
                _clients[i].MessageRecived(message);
            }
            catch (CommunicationObjectAbortedException coae)
            {
                _clients.RemoveAt(i);
            }
            catch(CommunicationObjectFaultedException cofe)
            {
                _clients.RemoveAt(i);
            }
        }
    }


    public void Message(string msg)
    {
        PublishMessage(msg);
    }
}


/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged, IClientCallback
{
    public ServiceController Service { get; set; }

    protected IPipeServiceContract Proxy { get; set; }
    protected DuplexChannelFactory<IPipeServiceContract> PipeFactory { get; set; }

    public ObservableCollection<ServerActivityNotification> Activity { get; set; }

    public override void BeginInit()
    {
        base.BeginInit();
        PipeFactory = new DuplexChannelFactory<IPipeServiceContract>(this, new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/PipeGUI"));
    }

    public MainWindow()
    {
        InitializeComponent();
        Activity = new ObservableCollection<ServerActivityNotification>();
        Service = ServiceController.GetServices().First(x => x.ServiceName == "Server Service");
        NotifyPropertyChanged("Service");
        var timer = new DispatcherTimer();
        timer.Tick += new EventHandler(OnUpdate);
        timer.Interval = new TimeSpan(0, 0, 0, 0, 850);
        timer.Start();

        if (Service.Status == ServiceControllerStatus.Running)
        {
            Proxy = PipeFactory.CreateChannel();
            Proxy.Connect();
        }
    }

    void OnUpdate(object sender, EventArgs e)
    {
        Service.Refresh();
        NotifyPropertyChanged("Service");

        StartButton.IsEnabled = Service.Status != ServiceControllerStatus.Running ? true : false;
        StopButton.IsEnabled = Service.Status != ServiceControllerStatus.Stopped ? true : false;

        if (PipeFactory != null && Service.Status == ServiceControllerStatus.Running)
        {
            Proxy = PipeFactory.CreateChannel();
            Proxy.Connect();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }

    private void OnStart(object sender, RoutedEventArgs e)
    {
        try
        {
            Service.Start();
        }
        catch
        {
            Service.Refresh();
        }
    }

    private void OnStop(object sender, RoutedEventArgs e)
    {
        try
        {
            if (Proxy != null)
            {
                Proxy.Disconnect();
                PipeFactory.Close();
            }
            Service.Stop();
        }
        catch
        {
            Service.Refresh();
        }
    }

    public void MessageRecived(string message)
    {
        Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
        {
            ServerActivityNotification log = new ServerActivityNotification { Activity = message, Occured = DateTime.Now };
            Activity.Add(log);
            ListBoxLog.ScrollIntoView(log);
            NotifyPropertyChanged("Activity");
        }));
    }

    private void OnHello(object sender, RoutedEventArgs e)
    {
        try
        {
            Proxy.Message(txtSendMessage.Text);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }
}

}

【问题讨论】:

    标签: c# .net wpf wcf named-pipes


    【解决方案1】:

    尝试将服务行为的UseSynchronizationContext属性设置为false

    [ServiceBehavior(UseSynchronizationContext = false)]
    class MyService
    {
    
    }
    
    [ServiceContract]
    public interface IMyService
    {
    
    }
    

    我相信默认设置为true,因此您当前正试图在同一线程上使用和运行 WCF 服务,从而导致死锁。

    无论如何,听起来您正试图在 WPF 应用程序的 UI 线程上使用 WCF 服务。通常,建议您在后台线程上执行可能需要长时间运行的任务,因为即使您的服务调用需要几秒钟/几分钟,这也会使界面保持响应。

    编辑:

    我尝试并成功复制了您的问题。尝试在 UI 线程上调用服务会导致 UI 冻结。但是,当我更改代码以在后台任务上调用服务时(见下文),我能够调用服务并接收回调:

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Task.Factory.StartNew(() =>
                {
                    var myService = DuplexChannelFactory<IMyService>.CreateChannel(new CallbackImplementation(),
                                                                                   new WSDualHttpBinding(),
                                                                                   new EndpointAddress(
                                                                                       @"http://localhost:4653/myservice"));
                    myService.CallService();
                    string s = "";
                });
        }
    

    我不得不承认,我不完全确定为什么会这样,任何关于 WCF 究竟如何管理托管服务实例的线程的任何说明都有助于弄清楚为什么会这样。

    【讨论】:

    • 感谢您的回答,我尝试了您的理论,但并没有太大的不同。当我使用实现回调接口的不同对象时,UI 线程没有冻结,但它也没有接收回调。当我直接在我的 WPF 窗口上再次实现我的回调接口时,它做了同样的事情并超时。我将在我的问题中发布我当前的代码。
    • 这听起来不错(您编辑的响应),但由于这是一个 GUI 应用程序,我不想每次我想向我的服务发送命令/消息时都创建一个新的后台线程。只要 gui 运行(当然服务正在运行),我也需要打开连接,因为我希望服务向 gui 发布有关服务当前正在运行的任务或任务期间是否发生错误的更新。跨度>
    • 你绝对应该在后台线程上完成你的服务——正式的建议是你应该做任何可能需要超过 50 毫秒的异步异步工作 (blog.stephencleary.com/2013/04/ui-guidelines-for-async.html)。结果返回后,应在 UI 线程上进行任何更新。无论如何,您应该优雅地处理任务上的错误。我不确定你对连接的意思 - 你肯定只希望它在服务调用期间打开?
    猜你喜欢
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 2014-05-29
    相关资源
    最近更新 更多