Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Creation of object in thread not accessible
Message
From
31/05/2011 12:09:14
 
 
To
31/05/2011 11:01:10
Timothy Bryan
Sharpline Consultants
Conroe, Texas, United States
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Environment versions
Environment:
C# 4.0
OS:
Windows XP SP2
Miscellaneous
Thread ID:
01512341
Message ID:
01512355
Views:
51
>Hi all,
>
>I have been moving some code to run in a background thread to speed up the performance. In my background worker I create the Configuration class which contains this property.
>
>
>/// <summary>
>/// Main Window State Setting
>/// </summary>
>public System.Windows.WindowState MainWindowState
>{
>	get { return OCSDApplication.Current.MainWindow.WindowState; }
>	set { OCSDApplication.Current.MainWindow.WindowState = value; }
>}
>
>
>Later when Application.InitializeComponent is run, this fails because of "InvalidOperationException" - "The calling thread cannot access this object because a different thread owns it".
>
>Is there a way when it is created to get the ownership of the class back on the main thread? This is WPF by the way.

Dispatcher ? This works and maybe you can adapt:
   public partial class SomeWindow : Window
    {
        public SomeWindow()
        {
            InitializeComponent();

            BackgroundWorker b = new BackgroundWorker();
            b.DoWork += new DoWorkEventHandler(DoWork);
            b.RunWorkerAsync();
        }

        public void SetMainWindowState(WindowState ws)
        {
            Application.Current.MainWindow.WindowState = ws;
        }

        public WindowState GetMainWindowState()
        {
            return Application.Current.MainWindow.WindowState;
        }

        void DoWork(object sender, DoWorkEventArgs e)
        {
            MainWindowState = WindowState.Maximized;
            WindowState test = MainWindowState;
        }

        private WindowState mainWindowState;
        public WindowState MainWindowState
        {
            set { Dispatcher.Invoke(DispatcherPriority.Normal, new Action<WindowState>(SetMainWindowState), value); }
            get
            {
                Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
                    { mainWindowState = this.GetMainWindowState(); }));
                return mainWindowState;
            }
        }
    }
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform