-1

In the following code snippet, How to update multiple labels? for example: Have several parameters in the update method instead of one parameter

 private void UIupdate(string name)
        {
            var timenow = DateTime.Now;
            if((DateTime.Now-dt).Milliseconds<=50)
                return;
            synchronizationcontext.Post(new SendOrPostCallback(o =>
            {
                
                lblFirstName.Text = "name" + (string)o;
                //lblLastName.Text = ?
                //lblZipCode.Text=?
            }),name );
            dt = timenow;
        }

1 Answers1

0

You can simply use the method parameters inside the lambda. The parameters are captured in a closure, and are available to all inner functions of a method.

private SynchronizationContext _synchronizationContext;
private Stopwatch _stopwatch = Stopwatch.StartNew();
private TimeSpan _lastUpdateTimestamp;

private void UIUpdate(string firstName, string lastName)
{
    TimeSpan timestamp = _stopwatch.Elapsed;
    if (timestamp < _lastUpdateTimestamp.Add(TimeSpan.FromMilliseconds(50))) return;
    _lastUpdateTimestamp = timestamp;

    _synchronizationContext.Post(_ =>
    {
        lblFirstName.Text = firstName;
        lblLastName.Text = lastName;
    }, null);
}

I also fixed your time-measuring logic. The Milliseconds counts only the milliseconds of the current second (has a value between 0 and 999). You probably intended to use the TotalMilliseconds. But even then your measurements would be dependent to the stability of the system clock. The system time can be adjusted by either user actions or automated procedures, so it cannot be trusted for measuring intervals.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104