WPF,STA线程异常

时间:2014-04-30 09:00:26

标签: c# wpf multithreading mvvm

我正在使用WPF(MVVM)应用。 使用2个按钮,一个用于从db加载数据,另一个用于删除所选项目。 点击Load按钮后会触发LoadCommand并调用StartLoadingThread

private void StartLoadingThread()
{
    ShowLoadProcessing(); // show some text on top of screen ("Loading in progress...")

    ThreadStart ts = delegate
    {
        LoadMyitems();

        System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (EventHandler)
        delegate
        {
            HideLoadProcessing(); // hide the text "Loading in progress..."
        }, null, null);
    };
    ts.BeginInvoke(ts.EndInvoke, null);
}

工作正常,现在当我选择一个项目并点击Delete按钮时,DeleteItemCommand被触发并调用StartDeletingThread

private void StartDeletingThread()
{
    ShowDeleteProcessing(); // Show on top of screen "Deleting in progress..."

    ThreadStart ts = delegate
    {
        DeleteSelectedItem();

        System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (EventHandler)
        delegate
        {
            HideDeletingProcessing();
        }, null, null);
    };
    ts.BeginInvoke(ts.EndInvoke, null);
}

启动StartDeletingThread时,我收到以下异常:

{"The calling thread must be STA, because many UI components require this."}

3 个答案:

答案 0 :(得分:0)

我认为你想要这样的东西,虽然我在WPF中有点新手,但你必须用WPF(Dispatcher)中的相同内容替换this.BeginInvoke。代码也可能无法编译(为Thread添加Action类型转换?),但想法是简单地启动线程(由于某些原因调用它,为什么?)并在该线程中在删除后调用UI操作。

private void StartDeletingThread()
{
    ShowDeleteProcessing(); // Show on top of screen "Deleting in progress..."
    new Thread(() =>
    {
        DeleteSelectedItem();
        this.BeginInvoke(() => HideDeletingProcessing());
    }.Start();
}

答案 1 :(得分:0)

尝试使用应用程序调度程序调用StartDeletingThread,如下所示:

Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,new       
Action(()=>StartDeletingThread())

答案 2 :(得分:0)

private void StartDeletingThread()
{
    ShowDeleteProcessing(); // Show on top of screen "Deleting in progress..."
    Task.Run(() =>
    {
        DeleteSelectedItem();
        Application.Current.Dispatcher.BeginInvoke((Action)HideDeletingProcessing);
    });
}

可能会在DeleteSelectedItem();爆炸。我知道我们都喜欢为不到一秒钟的动作显示进度条,但是当它导致StackOverflow上的问题时,为什么还要烦恼呢?

private void StartDeletingThread()
{
    DeleteSelectedItem();
}

完成并完成。我严重怀疑删除所选项目需要很长时间。

如果在某些极少数情况下确实如此......那么您需要在DeleteSelectedItem中找到触摸UI的位置,并使用应用程序的调度程序进行触摸。

(旁注,这是你在4.5中安全多线程的方法,使用async / await ... safe,只要你理解async void的影响,就是这样)

private async void StartDeletingThread()
{
    // we're in the UI thread
    ShowDeleteProcessing();
    await DeleteSelectedItem();
    // back in the UI thread
    HideDeletingProcessing();
}

private Task DeleteSelectedItem()
{
    // doing the work on a Task thread
    return Task.Run(() => DeleteSelectedItem = null);
}