BindingList.Add() 即使有锁也不能跨线程工作

BindingList.Add() doesn't work cross thread even with lock

刚学C#/.NET就遇到了这个问题

所以在我的解决方案中,我有 2 个项目:winforms UI 和带逻辑的 dll。在 dll 中,我有 BindingList,它为 UI.

中的 listBox 提供数据源

UI:

public partial class Form1 : Form
{
    private Class1 _class1;

    public Form1()
    {
        InitializeComponent();
        _class1 = new Class1(); // logic class insatce
        listBox1.DataSource = _class1.BindingList;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        _class1.Add();
    }

    private void button2_Click(object sender, EventArgs e)
    {
         _class1.Remove();
    }
}

逻辑class:

public class Class1
{
    public BindingList<string> BindingList { get; set; } = new BindingList<string>() ;

    public void Add()
    {
        var th = new Thread(() =>
        {
            lock (BindingList)
            {
                BindingList.Add("1");
            }
        }) {IsBackground = true};
        th.Start();
        // works fine
        //BindingList.Add("1");
    }

    public void Remove()
    {
        if (BindingList.Count > 1)
        {
            BindingList.RemoveAt(0);
        }
    }
}

所以问题是,如果我只是 运行 解决方案(ctrl + F5)一切正常,但在调试 mod(F5) 时,当我按下按钮时没有任何反应。我找到的所有答案都说:"use lock" 所以我使用锁和列表框仍然没有对向列表添加元素做出反应。请帮助我我做错了什么或者我错过了什么。

PS对不起我的英语。

首先要明确:您可能需要也可能不需要在这里使用 lock。这将取决于实际上是否有两个或更多线程访问 BindingList<T> 对象 并发 ,即字面意义上的同时(例如,两个或更多线程将项目添加到列表中,或者一个线程添加项目而另一个线程试图从列表中读取)。在您的代码示例中,情况似乎并非如此,因此没有必要。无论如何, lock 语句所做的事情与解决您所询问的特定问题所需的完全不同,并且在任何情况下仅当线程在同一对象上协同使用 lock 时才有效(如果仅一个线程调用 lock,但没有帮助。


基本问题是,当 UI 线程以外的其他线程引发这些事件时,ListBox 无法响应来自 BindingList 的事件。通常,解决方案是调用 Control.Invoke() 或类似的方法在 UI 线程中执行列表修改操作。但是在您的情况下,拥有 BindingList 的 class 不是 UI 对象,因此自然无法访问 Control.Invoke() 方法。

恕我直言,最好的解决方案是在涉及的 UI 个对象中保留 UI 线程知识。但是这样做需要 Class1 对象至少将列表的部分控制权移交给 UI 对象。一种这样的方法涉及向 Class1 对象添加一个事件:

public class AddItemEventArgs<T> : EventArgs
{
    public T Item { get; private set; }

    public AddItemEventArgs(T item)
    {
        Item = item;
    }
}

public class Class1
{
    public EventHandler<AddItemEventArgs<string>> AddItem;

    public BindingList<string> BindingList { get; set; }

    public Class1()
    {
        // Sorry, old-style because I'm not using C# 6 yet
        BindingList = new BindingList<string>();
    }

    // For testing, I prefer unique list items
    private int _index;

    public void Add()
    {
        var th = new Thread(() =>
        {
            string item = (++_index).ToString();

            OnAddItem(item);
        }) { IsBackground = true };
        th.Start();
    }

    public void Remove()
    {
        if (BindingList.Count > 1)
        {
            BindingList.RemoveAt(0);
        }
    }

    private void OnAddItem(string item)
    {
        EventHandler<AddItemEventArgs<string>> handler = AddItem;

        if (handler != null)
        {
            handler(this, new AddItemEventArgs<string>(item));
        }
    }
}

然后在你的 Form1:

public partial class Form1 : Form
{
    private Class1 _class1;

    public Form1()
    {
        InitializeComponent();
        _class1 = new Class1(); // logic class instance
        _class1.AddItem += (sender, e) =>
        {
            Invoke((MethodInvoker)(() => _class1.BindingList.Add(e.Item)));
        };
        listBox1.DataSource = _class1.BindingList;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        _class1.Add();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        _class1.Remove();
    }
}

这个主题的变体是在 Class1 中有两种不同的 "add" 方法。第一个是你现在拥有的,它最终使用了一个线程。第二个是 required 从 UI 线程调用的那个,它实际上会添加项目。在表单的 AddItem 事件处理程序中,不是直接将项目添加到列表,而是调用第二个 "add" 方法来为表单执行此操作。

哪个最好取决于您希望在 Class1 中进行多少抽象。如果您试图对其他 classes 隐藏列表及其操作,那么变体会更好。但是,如果您不介意从 Class1 代码之外的其他地方更新列表,上面的代码示例应该没问题。

另一种方法是使您的 Class1 对象具有线程感知能力,类似于BackgroundWorker 有效。您可以通过在创建 Class1 对象时捕获线程的当前 SynchronizationContext 来执行此操作(假设 Class1 对象是在您想要 return 到,添加一个项目)。然后在添加项目时,使用该上下文对象进行添加。

看起来像这样:

public class Class1
{
    public BindingList<string> BindingList { get; set; }

    private readonly SynchronizationContext _context = SynchronizationContext.Current;

    public Class1()
    {
        BindingList = new BindingList<string>();
    }

    private int _index;

    public void Add()
    {
        var th = new Thread(() =>
        {
            string item = (++_index).ToString();

            _context.Send(o => BindingList.Add(item), null);
        }) { IsBackground = true };
        th.Start();
    }

    public void Remove()
    {
        if (BindingList.Count > 1)
        {
            BindingList.RemoveAt(0);
        }
    }
}

在此版本中,不需要对 Form1 进行任何更改。

这个基本方案有很多变体,包括一些将逻辑放入专门的 BindingList<T> subclass 中的变体。例如(举出一对):
Cross-Thread Form Binding - Can it be done?
BindingList<> ListChanged event

最后,如果你真的想把东西组合在一起,你可以在列表发生变化时强制重置整个绑定。在这种情况下,您不需要更改 Class1,但需要更改 Form1:

public partial class Form1 : Form
{
    private Class1 _class1;

    public Form1()
    {
        bool adding = false;

        InitializeComponent();
        _class1 = new Class1(); // logic class instance
        _class1.BindingList.ListChanged += (sender, e) =>
        {
            Invoke((MethodInvoker)(() =>
            {
                if (e.ListChangedType == ListChangedType.ItemAdded && !adding)
                {
                    // Remove and re-insert newly added item, but on the UI thread
                    string value = _class1.BindingList[e.NewIndex];

                    _class1.BindingList.RemoveAt(e.NewIndex);
                    adding = true;
                    _class1.BindingList.Insert(e.NewIndex, value);
                    adding = false;
                }
            }));
        };
        listBox1.DataSource = _class1.BindingList;
    }

    // ...
}

我真的不推荐这种方法。但是如果你没有办法改变Class1,那就是你能做的最好的了。