0

以下是我的 ThreadSafe 函数的代码

public static void ThreadSafe(Action action)
        {
             System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
             new MethodInvoker(action));
        }

我正在使用此ThreadSafe函数来访问各种跨线程操作。它在其他类中工作正常,但是当我Comment在面板中添加用户控件时commentContainer,它显示以下错误。

跨线程操作无效异常

按照它的屏幕截图和代码: 在此处输入图像描述

我想通过comment字符串传递给这个控件。控制处理基于该值。我认为我使用此功能的方式是错误的。如果我的代码不正确,任何人都可以改进我的代码吗?如果正确,请告诉我如何解决这个问题?

另请注意,当我删除foreach循环时,后台工作人员工作正常。

setTopicInfo()代码:

public void setTopicInfo()
        {
            try
            {
                TopicInfo.Text = "Topic Views: " + dops.getVisiteds(tid) + " | " +
                    "People Involved: " + dops.getPeopleInvolved(tid) + " | ";
            }
            catch (Exception)
            { TopicInfo.Text = "[Some error occured while loading Topic Information. Please reopen or refresh this topic.] | "; }
        }
4

3 回答 3

2

Dispatcher.CurrentDispatcher returns a Dispatcher for the current thread. In this example, the ThreadSafe method was invoking the Action on the current thread rather than on the thread that created commentContainer (usually referred to as the UI thread.)

WinForms facilitates invoking code on the UI thread through the Control.Invoke and Control.BeginInvoke methods. A quick one-line fix to this example is replacing the call to Main.ThreadSafe with a call to commentContainer.Invoke or commentContainer.BeginInvoke. You may also take advantage of the BackgroundWorker.ProgressChanged event, as suggest by Bill Sambrone.

于 2013-08-01T18:07:05.600 回答
1

由于您使用的是 BackgroundWorker,因此您可以使用其报告进度的能力设置评论。通过设计器创建 ReportProgress 事件处理程序,或者如果您从代码创建 BWWorker,则将其添加到代码中。确保启用 ReportsProgress 的标志。

然后,在你的 foreach 循环中:

backgroundWorker1.ReportProgress(yourdatagoeshere)

然后在 backgroundWorker1_ReportsProgress 方法中,您将该数据传递给您的 addComment 方法。

于 2013-08-01T17:19:41.603 回答
1

您的 ThreadSafe 方法在从 bgw 线程调用时建立一个 Dispatcher。

这就是 MSDN 不得不说的Dispatcher.CurrentDispatcher

如果 Dispatcher 与当前线程没有关联,则将创建一个新的 Dispatcher。

请改用 Application.Dispatcher。参见例如这个 SO question

于 2013-08-01T14:14:04.230 回答