【问题标题】:WPF, calling server method in background workerWPF,在后台工作人员中调用服务器方法
【发布时间】:2010-11-11 04:25:33
【问题描述】:

我需要在 wpf 应用程序中检查服务器上的消息。我有自己的方法在服务器上加载消息-LoadRp()。

我想创建某种监听器,每 3 秒检查一次服务器上是否有新消息。

我在调度程序计时器滴答事件上调用加载消息的方法,它适合吗?任何其他解决方案。 wpf中的另一个线程可以调用定时器吗?

代码在这里:

    public MessangerWindow(PokecCommands pokecCmd)
    {
        InitializeComponent();

        PokecCmd = pokecCmd;

        _friendsData = PokecCmd.LoadFriends();
        friendsListBox.DataContext = _friendsData;

        _dispatcherTimer = new DispatcherTimer();
        _dispatcherTimer.Tick+=new EventHandler(DispatcherTimer_Tick);
        _dispatcherTimer.Interval = new TimeSpan(0,0,3);
        _dispatcherTimer.Start();
    }

    private void DispatcherTimer_Tick(object sender, EventArgs eventArgs)
    {
        try
        {

            //try load new message from sever
            RP message = PokecCmd.LoadRp();

            //arived message
            if (message != null)
            {
                //exist window
                if (_chatWindows.ContainsKey(message.Nick))
                {
                    _chatWindows[message.Nick].Show();
                }
                {
                    //create new Window
                    var chatWindow = new ChatWindow(PokecCmd, message);
                    _chatWindows.Add(message.Nick, chatWindow);
                    chatWindow.Show();
                }
            }
        }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.Message);
        }  
    }

适合用什么:

  • 没有后台线程的调度程序
  • 具有后台线程的调度程序
  • 多线程

【问题讨论】:

    标签: wpf multithreading timer


    【解决方案1】:

    如果您可以在检查服务器所需的时间内锁定您的 UI,那么按照您的操作方式使用 DispatcherTimer 即可。

    如果检查新消息的时间可能超过几毫秒,并且您希望 UI 在检查时能够做出响应,那么您应该使用多个线程。在这种情况下,一旦新数据到达,您将使用 Dispatcher.Invoke 来显示它。

    您在线程中检查消息的代码可能如下所示:

    //try load new message from sever 
    RP message = PokecCmd.LoadRp(); 
    
    //arived message 
    if( message != null )
        Dispatcher.Invoke(DispatcherPriority.Send, new Action(() =>
            { 
                //exist window 
                if (_chatWindows.ContainsKey(message.Nick)) 
                { 
                    _chatWindows[message.Nick].Show(); 
                } 
                { 
                    //create new Window 
                    var chatWindow = new ChatWindow(PokecCmd, message); 
                    _chatWindows.Add(message.Nick, chatWindow); 
                    chatWindow.Show(); 
                } 
            }
     );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多