Skip to content

多线程问题:调用线程无法访问此对象,因为另一个线程拥有该对象 #632

@cuiliang

Description

@cuiliang

有的情况下,为了避免模态窗口弹出时无法操作别的窗口,会对个别窗口使用新的线程运行。
示例代码:

public static class DispatcherBuilder
    {
        public static Dispatcher Build()
        {
            Dispatcher dispatcher = null;
            var manualResetEvent = new ManualResetEvent(false);
            var thread = new Thread(() =>
            {
                dispatcher = Dispatcher.CurrentDispatcher;
                var synchronizationContext = new DispatcherSynchronizationContext(dispatcher);
                SynchronizationContext.SetSynchronizationContext(synchronizationContext);

                manualResetEvent.Set();

                try
                {
                    Dispatcher.Run();
                }
                catch
                {
                    // ignore
                }
            }, maxStackSize: 1);
            thread.Priority = ThreadPriority.Normal;
            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Start();
            manualResetEvent.WaitOne();
            manualResetEvent.Dispose();
            return dispatcher;
        }
    }
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            var dispatcher = DispatcherBuilder.Build();

            dispatcher.InvokeAsync(() =>
            {
                try
                {
                    MainWindow mainWindow = new MainWindow();
                    mainWindow.Show();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }


            });
        }

使用HC库以后,这种情况会报线程错误:
image

WPF原生风格没有这个问题。
示例代码(threadtest分支):https://github.com/cuiliang/HandyControl/tree/threadtest

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions