1

バックグラウンド スレッドでカスタム userControl を動的に作成しようとしています。これは、新しいスレッドを作成する私の方法です:

var thread = new Thread(CreateItemInBackgroundThread);
thread.SetApartmentState(ApartmentState.STA);            
thread.Start();
thread.Join();

そして、これはメソッドCreateItemInBackgroundThreadです:

var uc = new MyUserControl();
UserControl item = uc;
AllControls.Add(item);
//Here I am trying to add control to a current Tab
foreach (var currentTab in _allTabs)
{
    currentTab.DocumentWindow.Dispatcher.BeginInvoke(new Action(() =>
                                                            {
                                                                if (tab.DocumentWindow.IsSelected)
                                                                {
                                                                    tempTab = tab;
                                                                    tempControl = item;
                                                                    finish = true;
                                                                }

                                                            }));
}

これは私の仕上げのプロパティです

bool finish
    {
        get { return _finish; }
        set
        {
            _finish = value;
            if (_finish)
            {
                tempTab.AnimatedCanvas.Dispatcher.BeginInvoke(new Action(() => tempTab.AnimatedCanvas.Children.Add(tempControl)));
            }
        } // Here I get error - The calling thread cannot access this object because a different thread owns it
    }

このエラーを回避する方法と、このエラーが発生した理由を教えてください。

4

2 に答える 2

0

エラーが示すように、別のスレッドがこのオブジェクトを所有しているため、このオブジェクトにアクセスできません。そのスレッドを使用して呼び出すことがInvoke(Delegate Method) できます。tempTab.InvokeRequired

于 2013-07-02T10:19:17.473 に答える