testing testing - 1 month ago 17
C# Question

Code should be executed one time after short delay

I have this

Timer
:

Timer delayTimer = new Timer();
delayTimer.Interval = 500;
delayTimer.Elapsed += (object sender, ElapsedEventArgs e) => {
Console.WriteLine("test");
textInputDialog.Show();
delayTimer.Stop();
};
delayTimer.Start();


Here I have the following problems:


  • Timer never stops. Code is executed every 500ms.

  • textInputDialog.Show();
    doesn't work (perhaps cause of problem above)



What is wrong with my code?

Alternative solutions:

This is an alternative to timer as Jens Horstmann mentioned. And this is called on the UI thread:

private async Task SendWithDelay()
{
await Task.Delay(500);
textInputDialog.Show();
}


Another alternative would be
NSTimer
:

NSTimer.CreateScheduledTimer(new TimeSpan(0,0,0,0,500), delegate {
textInputDialog.Show();
});


And to invoke a call on the UI thread you can use
InvokeOnMainThread
:

Timer delayTimer = new Timer();
delayTimer.Interval = 500;
delayTimer.Elapsed += (object sender, ElapsedEventArgs e) => {
delayTimer.Stop();
Console.WriteLine("test");
InvokeOnMainThread (() => {
textInputDialog.Show();
});
};
delayTimer.Start();

Answer

Stop the timer before you show the dialog:

delayTimer.Elapsed += (object sender, ElapsedEventArgs e) => {
    delayTimer.Stop();
    Console.WriteLine("test");
    textInputDialog.Show();
};

Also you probably used the wrong timer. Don't use System.Threading.Timer or System.Timers because this involves multithreading which does not work well with winforms or WPF. (This is probably the reason your MessageBox does not show - its called on the wrong thread)

In WPF you should use System.Windows.Threading.DispatcherTimer

Edit

In Winforms you should use System.Windows.Forms.Timer (see comments)

Comments