c# - 无法在静态上下文中访问非静态字段 'lblSystemStatus'

标签 c# multithreading winforms user-controls

我看过很多关于这个问题的帖子,但都没有帮助。 我有以下简单的代码:

private delegate void UpdateLabelCallback(Label lbLabel, string val);

防止非法跨线程调用的简单委托(delegate)。

private static readonly System.Threading.Timer TimerHalfASecond = new System.Threading.Timer(HalfASecondCallback, null,
        500, Timeout.Infinite);

线程计时器

private static void HalfASecondCallback(object state)
{
    UpdateLabel(lblSystemStatus, Resources.DesktopClock_timerOneSecond_Tick_CPU__ + _cpu.GetCpuCounter().ToString() + @"%");
    TimerHalfASecond.Change(500, Timeout.Infinite);
}

静态Threading.Timer 回调。 lblSystemStatus 错误显示

"cannot access non-static field 'lblSystemStatus' in static context"

private static void UpdateLabel(Label lbLabel, string val)
{
    if (lbLabel.InvokeRequired)
    {
        var d = new UpdateLabelCallback(UpdateLabel);
        lbLabel.Invoke(d, lbLabel, val);
    }
    else
    {

        lbLabel.Text = val;
    }
}

静态 UpdateLabel 方法。

那么问题是: 当标签不是静态的并且回调要求它们是静态的时,我如何更新控件上的标签?

最佳答案

您将计时器声明为 private static readonly .如果计时器在类(控件)的实例中运行,我不会这样做。如果你不成功 static ,其他方法不必,您可以安全地使用实例变量(如果您有两个类实例,计时器可能会发生冲突)。

另一种方法是提供 stateTimer包含标签的构造函数,或 Func<Label检索标签。对于第一个选项,这意味着您必须延迟创建计时器,直到创建标签。

示例:

new System.Threading.Timer(HalfASecondCallback, this.lblStatusText,
    500, Timeout.Infinite);

那么您的处理程序可能是:

private static void HalfASecondCallback(object state)
{
    Label l = state as Label; // in fact lblSystemStatus

    if (l != null)
    {
        UpdateLabel(l, Resources.DesktopClock_timerOneSecond_Tick_CPU__ + _cpu.GetCpuCounter().ToString() + @"%");
        TimerHalfASecond.Change(500, Timeout.Infinite);
    }
}

关于c# - 无法在静态上下文中访问非静态字段 'lblSystemStatus',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33732556/

相关文章:

c# - 停止从用户代理继承

c# - 产卵 BackgroundWorkers

c# - 多线程

JavaScript:异步函数是否创建新线程?

c# - 在 DAL 层使用 appsettings

c# - Mysql 更新查询未运行 ASP.NET

c# - 当我在 Visual Studio Community 2017 中创建一个 asp.net 项目时,没有创建 .csproj 文件

c# - 如何撤销 WCF 中的客户端证书?

c# - 如何通过编码点击一个按钮?

vb.net - 收到错误 System.ArgumentNullException 未处理,值不能为 null。参数名称: activationContext