简体   繁体   中英

Anonymous functions in Timer C#

Why this is do not work? I am do not understand what is here wrong . . .

  public static void Pause_ForCreate(out Timer _T,  ref Label _ChangeImageEllipse)
        {
            Label d = _ChangeImageEllipse;
            _T = new Timer(2000);
            // _T.Elapsed += EllipseVisible_Tick;
            _T.Elapsed += (sender, e) => EllipseVisible_Tick((object)d, e);
            _T.AutoReset = false;
            _T.Start();

        }
 private static void EllipseVisible_Tick(object Sender, ElapsedEventArgs E)
        {
           ((Ellipse)((Label)Sender).Content).Visibility = Visibility.Visible;
        }

You should use a DispatcherTimer instead of a Timer, because its Tick handler is called in the UI thread (as opposed to an Elapsed handler of a Timer)

Then you don't need to pass the Label as ref parameter, because you don't want to change the reference inside the method. Also, since you are not returning anything you can remove the out from the Timer _T , and return the timer instead. The label d , is unnecessary and you can send the _ChangeImageEllipse directly to the EllipseVisible_Tick method, but since that method only does one small thing, the method might not be needed at all.

I would refactor it like this:

public static DispatcherTimer Pause_ForCreate(Label _ChangeImageEllipse)
{
    var t = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
    t.Tick += (s, e) => _ChangeImageEllipse.Visibility = Visibility.Visible;
    t.Start();
    return t;
}

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