【问题标题】:WPF call to library not working (thread problem)WPF 调用库不起作用(线程问题)
【发布时间】:2020-09-08 10:01:56
【问题描述】:

我有一个第三方库,我用它来生成某种消息。

我的代码在控制台应用程序中运行,但是当我从 WPF .xaml.cs 类调用它时,它什么也不做!

在调试中,我进入了 Produce(Message) 函数,然后什么都没有!我没有发现任何异常,也没有进入下一行。

完全相同的代码在控制台应用程序中完美运行。

帮助:(

        try
        {
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            _producer.Produce(message);
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }

【问题讨论】:

    标签: c# wpf multithreading invoke


    【解决方案1】:

    这是我为此目的编写的一个小类:

    public class WaitCursor : IDisposable
    {
        private Cursor _previousCursor;
    
        public WaitCursor()
        {
            _previousCursor = Mouse.OverrideCursor;
    
            Application.Current.Dispatcher.Invoke(() => Mouse.OverrideCursor = Cursors.Wait);
        }
    
        #region IDisposable Members
        public void Dispose()
        {
            Application.Current.Dispatcher.Invoke(() => Mouse.OverrideCursor = _previousCursor);
        }
        #endregion
    }
    

    像这样使用它:

    using (var cursor = new WaitCursor())
    {
        // Your long-running code here
    }
    

    【讨论】:

    • 非常好!您可以考虑从class 切换到struct 作为WaitCursor 的类型,以避免一次分配的微小开销(微优化,我知道!)。
    【解决方案2】:

    我已经通过将我的代码包含在一个方法中并执行以下操作来修复它:

            Task.Factory.StartNew(() =>
            {
                ProduceMessage();
            });
    

    【讨论】:

    • 请注意,Task.Factory.StartNew 应该只是 Task.Run,并且应该等待:await Task.Run(() => ProduceMessage());
    • 这只是通过将问题推送到另一个线程来解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 2020-03-10
    相关资源
    最近更新 更多