user2519971
user2519971

Reputation: 345

displaying Busy Indicator while user authentication on a thread : Threading error (The calling thread cannot access this object)

I am developing a WPF application and following MVVM approach. I have to show the busy indicator on my log-in screen when an user click on the 'Enter' Button means while authenticating. On 'Enter' button I am having an ICommand named 'EnterCommand' which then check the authentication and then on successful authentication loads the MainWindow.

private ICommand _EnterCommand;
public ICommand EnterCommand
{
    get
    {
        return _EnterCommand ?? (_EnterCommand = new DelegateCommand(() =>
        {
            Thread objThread = new Thread(LoadApplication);
            objThread.SetApartmentState(ApartmentState.STA);
            objThread.Start();

        }));
    }
}

IsBusy propery is bound to this showprogress

private bool _ShowProgress = false;
public bool ShowProgress
{
    get { return _ShowProgress; }
    set
    {
        if (_ShowProgress != value)
        {
            _ShowProgress = value;
            FirePropertyChanged("ShowProgress");
        }
    }
}

I am creating a thread on this command then setting the IsBusy property from (bool Property name : ShowProgress) MVVM.

in LoadApplication:

public void LoadApplication()
{
    ShowProgress= true;
    if (AuthenticateUser)
    {
        MainWindow objMainWindow = new MainWindow();
        objMainWindow.Show();
        Application.Current.MainWindow.Close();
    }
    ShowProgress= false;
}

Error: objMainWindow.Show() is throwing error that - The calling thread cannot access this object because a different thread owns it.

Also in App.xaml I have set StartupUri as my 'Log-in' window.

This is able to show the Busy Indicator as soon as user clicks on the 'Enter' button however failed while showing the mainWindow.

I have to show the busyindicator as long as my MainWindow (which is home screen) is not launched.

Error: objMainWindow.Show() in LoadApplication() is throwing error that - The calling thread cannot access this object because a different thread owns it.

Stack Trace:
   at System.Windows.Markup.XamlReader.RewrapException(Exception e, Uri baseUri)
   at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader, XamlObjectWriter currentWriter)
   at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlObjectWriter objectWriter)
   at System.Windows.FrameworkTemplate.LoadOptimizedTemplateContent(DependencyObject container, IComponentConnector componentConnector, IStyleConnector styleConnector, List`1 affectedChildren, UncommonField`1 templatedNonFeChildrenField)
   at System.Windows.FrameworkTemplate.LoadContent(DependencyObject container, List`1 affectedChildren)
   at System.Windows.StyleHelper.ApplyTemplateContent(UncommonField`1 dataField, DependencyObject container, FrameworkElementFactory templateRoot, Int32 lastChildIndex, HybridDictionary childIndexFromChildID, FrameworkTemplate frameworkTemplate)
   at System.Windows.FrameworkTemplate.ApplyTemplateContent(UncommonField`1 templateDataField, FrameworkElement container)
   at System.Windows.FrameworkElement.ApplyTemplate()
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.StackPanel.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.Grid.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.Control.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.Grid.MeasureCell(Int32 cell, Boolean forceInfinityV)
   at System.Windows.Controls.Grid.MeasureCellsGroup(Int32 cellsHead, Size referenceSize, Boolean ignoreDesiredSizeU, Boolean forceInfinityV)
   at System.Windows.Controls.Grid.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at MS.Internal.Helper.MeasureElementWithSingleChild(UIElement element, Size constraint)
   at System.Windows.Controls.ContentPresenter.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Documents.AdornerDecorator.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.Border.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Window.MeasureOverrideHelper(Size constraint)
   at System.Windows.Window.MeasureOverride(Size availableSize)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Interop.HwndSource.SetLayoutSize()
   at System.Windows.Interop.HwndSource.set_RootVisualInternal(Visual value)
   at System.Windows.Interop.HwndSource.set_RootVisual(Visual value)
   at System.Windows.Window.SetRootVisual()
   at System.Windows.Window.SetRootVisualAndUpdateSTC()
   at System.Windows.Window.SetupInitialState(Double requestedTop, Double requestedLeft, Double requestedWidth, Double requestedHeight)
   at System.Windows.Window.CreateSourceWindow(Boolean duringShow)
   at System.Windows.Window.CreateSourceWindowDuringShow()
   at System.Windows.Window.SafeCreateWindowDuringShow()
   at System.Windows.Window.ShowHelper(Object booleanBox)
   at System.Windows.Window.Show()
   at RBS.MIB.DS.Reporting.UI.MainViewModelStartupWindow.LoadApplication() in C:\DSReporting\trunk\Projects\csharp\UI\RBS.MIB.DS.Reporting.UI\StartUpWindow\StartupViewModel\MainViewModelStartupWindow.cs:line 104
   InnerException: System.InvalidOperationException
   Message=The calling thread cannot access this object because a different thread owns it.

Upvotes: 0

Views: 258

Answers (1)

Krish
Krish

Reputation: 376

Please try this:

private BackgroundWorker _BgWorker;

public LoginFormViewModel()
{
    _BgWorker = new BackgroundWorker();
    _BgWorker.DoWork += new DoWorkEventHandler(bgw_DoWork);
    _BgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
    _BgWorker.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
    _BgWorker.RunWorkerAsync();
}

void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // write your code to check authentication
}

void bgw_DoWork(object sender, DoWorkEventArgs e)
{
   // write you code to open window
}

void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // write the code for busy indicator like 
    ShowProgress= true;
}

Hope this may help you.

Upvotes: 1

Related Questions