调用线程必须为 STA,因为许多 UI 组件都需要。

调用线程必须为 STA,因为许多 UI 组件都需要。

ThreadPool.QueueUserWorkItem(delegate
{
    SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
    SynchronizationContext.Current.Post(pl =>
    {
                        
    }, null);
});

 

 后台代码不能直接操作UI控件,需要控制,就要通过这个Dispatcher。

类库程序不需要使用Dispatcher,而是页面需要程序的时候使用Dispatcher

方式一:

Application.Current.Dispatcher.Invoke((Action)(() => { code }));

方式二:

Action action1 = () => { };
documentList[friendId].Dispatcher.BeginInvoke(action1);

方式三:

Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Loaded, new Action(() =>
{
                            
}));

 

调用线程无法访问此对象,因为另一个线程拥有该对象。

出错原因:

多线程之间,主线程的控制等等是被保护的。

 

Task p = new Task(state =>
            {

            }, "我是父任务");
            p.ContinueWith(t =>
            {

                //Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
                //{
                //    WindowLogin.Instance().Close();
                //    MainWindow.Instance().Show();
                //}));
            });
            p.Start();

 后台异步

BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += (o, e) =>
                {
                    List<GetConversationListResult> result = data.ToParse<List<GetConversationListResult>>();
                   
                    foreach (V2TIMConversationInfo item in conversationList)
                    {
                        var vm = MainWindowViewModel.CreateInstance();
                        vm.conversationList.Add(item);
                    }
                };
                worker.RunWorkerCompleted += (o, e) =>
                {

                };
                worker.RunWorkerAsync();

 该类型的 CollectionView 不支持从调度程序线程以外的线程对其 SourceCollection 进行的更改。

ThreadPool.QueueUserWorkItem(delegate
            {
                SynchronizationContext.SetSynchronizationContext(new
                    DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
                SynchronizationContext.Current.Post(pl =>
                {
                    //里面写业务内容
    }, null);
});

 

posted @ 2023-04-09 02:43  microsoft-zhcn  阅读(4025)  评论(0)    收藏  举报