-2

可能重复:
WPF 中的 DoEvent() 等价物

我几天前问了这些问题,但没有得到太多有用的评论,因为我在 WPF 中是全新的并且不知道线程但是我今天必须交付我的任务并且需要尽快完成这些,上次我使用 Windows 窗体和我的函数使用事件();因为我将我的程序移到 WPF 并做 Event 它不再支持我需要转换这些函数

PS:这些功能用于将数据发送到 com 端口和更新 UI

 private void Send(byte[] cmd)
        {
            bWaiting = true;
            MyResp = new byte[0];

            WriteOnPort(cmd);

            while (bWaiting == true) // here is a problem
            {
                System.Windows.Forms.Application.DoEvents();  // here is a problem
                System.Threading.Thread.Sleep(15);
            }
        }

我真的需要在今天之前完成这些并且不知道如何解决任何帮助都会很棒

4

2 回答 2

2

一个简单的选择是线程化WriteOnPort它的方式比破解 UI 更新更好。

根据您的需要,这里有 2 个示例

  1. 简单的线程方法。

    private void Send(byte[] cmd)
    {
        ThreadPool.QueueUserWorkItem((o) => WriteOnPort(cmd));
    }
    
  2. using BackroundWorker,因此您可以在完成Completed时使用该事件WriteOnPort

    private void Send(byte[] cmd)
    {
        var worker = new BackgroundWorker();
        worker.RunWorkerAsync(cmd);
        worker.DoWork += (s, e) =>
        {
           WriteOnPort(e.Argument as byte[]);
        };
        worker.RunWorkerCompleted += (cs, ce) =>
        {
           // do anything you need on completion
        };
    }
    

System.Windows.Forms.Application.DoEvents()是一个可怕的;e hack,永远不应该在 winforms 中以这种方式使用,并且试图找到一种方法在 WPF 中做同样的 hack 只是愚蠢的,玩一玩Threading并找到正确的方法来做事情,否则就像黑客一样这有一天会回来困扰你。

于 2013-01-29T02:16:03.187 回答
-2
public static void DoEvents()
{
    Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,                                        new Action(delegate { }));
}
于 2013-01-29T02:24:31.750 回答