【问题标题】:C# - Listbox not updated when an entry is added to the list in a seperate threadC# - 将条目添加到单独线程中的列表时未更新列表框
【发布时间】:2015-02-16 02:17:43
【问题描述】:

我有一个将日志打印到列表框的静态类,因此我可以全局使用它,因此我使用了在我的 cls_globalvariables 静态类中定义的 BindingList 的全局实例。我在 UI 构造函数中将 BindingList 绑定到 UI 的列表框。

public static class cls_globalvariables
{
    public static BindingList<string> logList = new BindingList<string>();
  ....
}

static class LOGS
{

    public static void LOG_PRINT(string logMessage, bool isNotError)
    {
        string now = DateTime.Now.ToString();
        try
        {
            if (logMessage == "") return;
            if (!isNotError)
                logMessage = "<<<ERROR>>>" + logMessage;

            // Output to text file.
            using (StreamWriter w = System.IO.File.AppendText(cls_globalvariables.systemlogpath))
            {
                w.WriteLine("[" + now + "][" + logMessage + "]");
                w.Close();
            }
            // Save to memory
            cls_globalvariables.logList.Add("[" + now + "][" + logMessage + "]");
        }
        catch (Exception)
        { }
    }
}

public partial class Form1: Form
{
    public Form1()
    {
        InitializeComponent();
        listBox1.DataSource = cls_globalvariables.logList;
    }
}

但是,我只在后台工作程序中调用 LOGS.LOG_PRINT,因此它在另一个线程中执行。列表框会延迟更新,直到后台工作人员完成其进程。我错过了什么吗?

【问题讨论】:

    标签: c# multithreading listbox backgroundworker


    【解决方案1】:

    您不应该在后台线程中更新 BindingList 实例,因为您将它绑定到主用户界面线程。用户界面控件不设计为从创建它的线程以外的任何线程调用。

    因此,我建议您的后台线程使用新消息回调主线程,然后主线程将消息添加到绑定列表中。

    将 SynchronizationContext.Current 从主线程传递到后台线程,然后在 LOGS.LOG_PRINT 方法中,您应该使用 lambda 调用 SynchronizationContext 的 Post 方法来更新列表。类似于以下内容...

    _syncContext.Post((_) => cls_globalvariables.logList.Add(str), null);
    

    其中 str 是新构造的日志字符串。

    【讨论】:

    • 如何让后台线程回调到主线程?这不会改变 LOGS_PRINT() 的实现,以至于我只能在另一个线程中使用 LOGS_PRINT() 吗?
    猜你喜欢
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 2013-12-23
    • 1970-01-01
    • 2013-05-30
    • 2016-04-24
    • 1970-01-01
    相关资源
    最近更新 更多