【问题标题】:Any one have good sample of thread safe call?任何人都有很好的线程安全调用示例?
【发布时间】:2011-06-23 06:18:48
【问题描述】:

我有一个函数LoadData 有大量的WinForm 控件,它将数据从数据库加载到控件中。 现在它变得非常慢,我应该使用线程,如果是,那么请建议一个好的示例,我已经尝试过MSDN sample

但这对我没有用,它需要对我的代码进行大量更改。

【问题讨论】:

  • 你必须明确你正在加载什么样的数据,以及如何加载;以及你正在用它做什么
  • 另外,一般来说,线程几乎总是需要大量的返工,特别是如果核心代码的设计没有考虑线程......
  • 最好的办法是查看加载了多少数据,看看是否找不到加载子集的方法。

标签: c# winforms multithreading c#-4.0 parallel-processing


【解决方案1】:

我假设您有很多与 UI 交互的代码,并且您想从后台线程执行。

你可以添加这样的方法:

private static void UpdateControl(Control control, Action action)
{
    if (control.InvokeRequired)
        control.Invoke(action);
    else
        action();
}

用法:

 textBox.Text = "Something";

新的

 UpdateControl(textbox, () => { textBox.Text = "Something" });

或扩展方法,以缩短使用时间

public static class ControlExtension
{
    public static void UpdateControl(this Control control, Action<Control> action)
    {
        if (control.InvokeRequired)
            control.Invoke((Action)(() => action(control)));
        else
            action(control);
    }
}

用法:

textBox.UpdateControl(arg => arg.Text = "Something");

【讨论】:

  • 非常简洁的答案。扩展方法 IYAM 的主要候选者
  • @Alex Aza:如果函数有 8/10 个控件或者可能更多,那么 control.InvokeRequired 和 control.Invoke 会同时执行..?
  • @Akhil - 不确定我是否理解。 InvokeRequiredInvoke 一个接一个地执行,而不是同时执行。如果调用来自非 UI 线程,control.InvokeRequired 将返回 true。
【解决方案2】:

您可以使用 .NET 4 中的 TPL 以一种可能更简单的方式来处理这个问题。您需要做的就是传递一个适当的TaskScheduler。使用从 UI 上下文创建的 TaskScheduler,任何调用都可以轻松包装到 Task 中,该 Task 将根据需要在 UI 线程上执行。

详情见我的blog post on the subject

【讨论】:

    【解决方案3】:

    查看BackgroundWorker

    var bw = new BackgroundWorker();
    bw.DoWork += (s, e) => e.Result = getAllBoxers();
    bw.RunWorkerCompleted += (s, e) =>
        {
            var boxers = e.Result as List<Boxer>;
            dgvBoxers.DataSource = boxers;
        };
    bw.RunWorkerAsync();
    

    确保永远不要做任何影响DoWork 中的 GUI 的事情,因为 WinForms 不是线程安全的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-06
      • 2016-11-29
      • 2015-10-31
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2010-10-07
      相关资源
      最近更新 更多