工作线程添加BindingList时跨线程操作异常

发布于 2024-09-14 14:35:35 字数 628 浏览 5 评论 0原文

我有一个工作线程需要将项目添加到 BindingList。但是,BindingList 是数据绑定到 DataGridView 的。因此,当我尝试添加到列表中时,我收到 InvalidOperationException (跨线程操作无效:从创建它的线程以外的线程访问控制。)

通常,对于此异常,您可以会做:

if(winformControl.InvokeRequired) {
    winformControl.Invoke(MethodDelegate);
}

但是,数据绑定使事情变得混乱,因为看不到 Winform 控件。我所拥有的只是以下行,它引发异常:

ClassInstance.MyBindingList.Add(myObject);

如果您有专门针对此场景的解决方案,那就太好了。

如果没有,我怎样才能让工作线程告诉我的主线程执行特定的方法(使用工作线程提供的几个参数)?这可能是一个更好的选择,因为我的工作线程目前实际上正在做很多事情(例如写入数据库),并且我不确定一切是否都是线程安全的。我是一名学生,对多线程还很陌生,这确实还不是我的强项。

I have a worker thread that needs to add items to a BindingList. However, the BindingList is databound to a DataGridView. So, when I try to add to the list, I get an InvalidOperationException (Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.)

Normally for this exception you would do:

if(winformControl.InvokeRequired) {
    winformControl.Invoke(MethodDelegate);
}

However, the databinding confuses things, as there is no Winform control in sight. All I have is the following line, which throws the exception:

ClassInstance.MyBindingList.Add(myObject);

If you have a solution specifically for this scenario, great.

If not, how can I get the worker thread to tell my main thread to perform a particular method (with several parameters supplied by the worker thread)? This may be a preferable option, since my worker thread is actually doing a bunch of stuff at the moment (like writing to the database), and I'm not sure if everything is thread-safe. I'm a student, and new to multithreading, and it really is not my forte yet.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

无语# 2024-09-21 14:35:35

这里的一种选择是告诉 BindingList 使用同步上下文,像这样 - 然而,这可以说不是最好的方法。我想知道您是否可以通过事件或类似事件公开您的数据(而不是直接添加到列表中),然后让您的 UI 通过发送到正确的线程并添加到 UI 模型来处理该事件。

One option here is to tell BindingList<T> to use the sync-context, like this - however, this is arguably not the best approach. I wonder if you could expose your data via an event or similar (rather than adding to the list directly) - then have your UI handle the event by sending to the right thread and adding to the UI model.

小巷里的女流氓 2024-09-21 14:35:35

在您的辅助类构造函数中,尝试以下操作:

private System.Threading.SynchronizationContext mContext = null;

/// <summary>
/// Constructor for MyBackgroundWorkerClass
/// </summary>
public MyBackgroundWorkerClass(System.Threading.SynchronizationContext context)
{
    mContext = context;
}

然后,当您需要在 UI 线程上调用某些内容时:

private void CallOnTheUiThread(object dataToPassToUiThread)
{
    // Make sure the code is run on the provided thread context.
    // Make the calling thread wait for completion by calling Send, not Post.
    mContext.Send(state =>
        {
            // Change your UI here using dataToPassToUiThread.  
            // Since this class is not on a form, you probably would 
            // raise an event with the data.
        }
    ), null);
}

当从 UI 线程上的表单创建您的辅助类时,这就是您将作为同步上下文传递的内容。

private void Form1_Load(object sender, EventArgs e)
{
    var worker = new MyBackgroundWorkerClass(SynchronizationContext.Current);
}

In your worker class constructor, try this:

private System.Threading.SynchronizationContext mContext = null;

/// <summary>
/// Constructor for MyBackgroundWorkerClass
/// </summary>
public MyBackgroundWorkerClass(System.Threading.SynchronizationContext context)
{
    mContext = context;
}

Then, when you need to invoke something on the UI thread:

private void CallOnTheUiThread(object dataToPassToUiThread)
{
    // Make sure the code is run on the provided thread context.
    // Make the calling thread wait for completion by calling Send, not Post.
    mContext.Send(state =>
        {
            // Change your UI here using dataToPassToUiThread.  
            // Since this class is not on a form, you probably would 
            // raise an event with the data.
        }
    ), null);
}

When creating your worker class from a form on the UI thread, this is what you would pass as the synchronization context.

private void Form1_Load(object sender, EventArgs e)
{
    var worker = new MyBackgroundWorkerClass(SynchronizationContext.Current);
}
再浓的妆也掩不了殇 2024-09-21 14:35:35

您可以向主、UI、线程触发一个事件,并且有:

if (this.InvokeRequired)
{
    this.Invoke(...);
}

因此您正在主窗口本身上进行测试。

You can fire an event to the main, UI, thread and there have:

if (this.InvokeRequired)
{
    this.Invoke(...);
}

so you are testing on the main Window itself.

天气好吗我好吗 2024-09-21 14:35:35

如果您能够满足要求,BackgroundWorkers 很容易实现。

定义一个在后台线程上运行的 DoWork 方法,例如保存到数据库。当 DoWork 完成时,将调用 RunWorkerCompleted 方法。 RunWorkerCompleted 在 UI 线程上运行,您可以毫无问题地更新视图的列表。

// on the UI thread
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += DoWork;
worker.RunWorkerCompleted += RunWorkerCompleted;
worker.RunWorkerAsync("argument");

活动:

static void DoWork(object sender, DoWorkEventArgs e)
{
    e.Result = "4";
}

static void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Error == null)
    {
        string a = (string)e.Result;
        Console.WriteLine(a);
    }
    else
    {
        Console.WriteLine(e.Error.Message);
    }
}

BackgroundWorkers are easy to implement if you are able to given the requirements.

Define a DoWork method that runs on a background thread such as saves to the database. The RunWorkerCompleted method is called when DoWork finishes. RunWorkerCompleted runs on the UI thread, and you can update the view's list with no problems.

// on the UI thread
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += DoWork;
worker.RunWorkerCompleted += RunWorkerCompleted;
worker.RunWorkerAsync("argument");

Events:

static void DoWork(object sender, DoWorkEventArgs e)
{
    e.Result = "4";
}

static void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Error == null)
    {
        string a = (string)e.Result;
        Console.WriteLine(a);
    }
    else
    {
        Console.WriteLine(e.Error.Message);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文