简体   繁体   中英

Cannot access non-static field 'lblSystemStatus' in static context

I have seen numerous posts on this problem, none of which have assisted. I have the simple following code:

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

A simple delegate to prevent Illegal Cross Thread Calls.

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

A threading timer

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

The static Threading.Timer Callback. The lblSystemStatus is errored showing

"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;
    }
}

The static UpdateLabel method.

So the question is: How can I update the labels on the control when they are not static and the callback demands that they are?

You are declaring your timer as a private static readonly . I won't do that if the timer runs in an instance of the class (control). If you don't make it static , the other methods don't have to and you can safely use instance variables (if you have two class instances, the timer could clash).

Another way is to provide the state to the Timer constructor to include the label, or a Func<Label to retrieve the label. For the first option it means you have to delay the creation of the timer until the label was created.

Sample:

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

Then your handler could be:

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);
    }
}

您可以创建一些静态字段,将您的标签分配给该字段并在静态上下文中使用它

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM