C#WPF正在从工作线程更新UI

本文关键字:线程 更新 UI 工作 C#WPF | 更新日期: 2023-09-27 18:00:46

using System;
using System.Linq;
using Microsoft.Practices.Prism.MefExtensions.Modularity;
using Samba.Domain.Models.Customers;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common;
using Samba.Presentation.Common.Services;
using System.Threading;

namespace Samba.Modules.TapiMonitor
{
    [ModuleExport(typeof(TapiMonitor))]
    public class TapiMonitor : ModuleBase
    {
        public TapiMonitor()
        {
            Thread thread = new Thread(() => OnCallerID());
            thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
            thread.Start();
        }
        public void CallerID()
        {
            InteractionService.UserIntraction.DisplayPopup("CID", "CID Test 2", "", "");
        }
        public void OnCallerID()
        {
            this.CallerID();
        }
    }
}

我正试图向用C#制作的开源软件包添加一些东西,但我遇到了问题。上面(简化(示例的问题是,一旦调用InteractionService.UserIntration.DisplayPopup,我就会得到一个异常"调用线程无法访问此对象,因为其他线程拥有它"。

我不是一个C#程序员,但我已经尝试了很多方法来解决这个问题,比如Delegates、BackgroundWorkers等,但到目前为止还没有一个对我有效。

有人能帮我吗?

C#WPF正在从工作线程更新UI

考虑通过Dispatcher在UI线程上调用该方法。在您的情况下,我认为您应该将UI调度器作为参数传递给您所描述的类型的构造函数,并将其保存在字段中。然后,打电话时,您可以执行以下操作:

if(this.Dispatcher.CheckAccess())
{
    InteractionService.UserInteration.DisplayPopup(...);
}
else
{
    this.Dispatcher.Invoke(()=>this.CallerID());
}

您可以编写自己的DispatcherHelper来从ViewModels访问Dispatcher。我认为它对MVVM很友好。我们在应用程序中使用了这样一个实现:

public class DispatcherHelper
    {
        private static Dispatcher dispatcher;
        public static void BeginInvoke(Action action)
        {
            if (dispatcher != null)
            {
                dispatcher.BeginInvoke(action);
                return;
            }
            throw new InvalidOperationException("Dispatcher must be initialized first");
        }
        //App.xaml.cs
        public static void RegisterDispatcher(Dispatcher dispatcher)
        {
            DispatcherHelper.dispatcher = dispatcher;
        }
    }