首页 > 解决方案 > Reactive Threading Exception: 调用线程必须是 STA,因为很多 UI 组件都需要这个

问题描述

我正在使用以下代码

    public IObservable<Unit> RunReport()
    {
        return Observable.Start(() =>
        {
            string selectedPath = null;

            //System.Windows.Application.Current.Dispatcher.Invoke(delegate
            //{
                OpenFileDialog ofd = new OpenFileDialog();

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    selectedPath = ofd.FileName;
                }
                else
                {
                    selectedPath = null;
                }
            //});
        });
    }

这会引发The calling thread must be STA, because many UI components require this异常。

如果我取消注释上面的 3 行,那么我不会得到异常,但这感觉不是解决这个问题的正确方法,因为我看到的关于 Observables 和线程问题的许多其他答案建议使用Observable.Start(() => ...).ObserveOnDispatcher();.

我已经尝试过该选项,但错误仍然存​​在!

标签: c#wpfsystem.reactivereactiveui

解决方案


推荐阅读