Alternative to Thread.Sleep that block - c#

I am looking for an alternative to calling Thread.Sleep which does not block the thread but instead returns the thread back into the thread pool. Does such a thing exist?

Use Task.Delay
await Task.Delay(delay);

If the thread is returning to the pool, then it isn't going to do any more work in the method in question. Make the next bit of the method a separate method, and create a Timer that calls it.

You can use also a Timer for example:
using System.Timers;
private void Main()
{
Timer t = new Timer();
t.Interval = 5000; // 5 seconds
t.AutoReset = false;
t.Elapsed += new SleepDone(TimerElapsed);
t.Start();
}
private void SleepDone(object sender, ElapsedEventArgs e)
{
Console.WriteLine("HERE WHAT COME AFTER SLEEP");
}

Related

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();
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)
Here is a solution without async/await
It also happen to fit in a single statement, which is rather elegant.
This is a C#, cross-platform solution to perform an action after a delay.
Also works for a recurring task.
using System.Threading;
var delayTimer = new Timer((state) => // Create timer, forget about it
InvokeOnMainThread(() => // Fire on main thread
textInputDialog.Show() // Your code goes here
),
null, // Ignore the state
5 * 1000, // 5 seconds until the 1st fire
Timeout.Infinite); // Do not repeat
Something like this worked for me:
private async Task DelayedShow()
{
await Task.Delay(500);
await _loadPop.textInputDialog.Show();
}
Remember to call the method like this:
BeginInvokeOnMainThread(() => DelayedShow());

Best way to make a polling thread

In my application I need a background thread that contacts a server every N seconds...
I made it in this way:
Task.Factory.StartNew (() => {
while(true)
{
Thread.Sleep (10000);
...do my stuff...
}
});
This solution works fine but I need to know if there is a better one. (for example: is Task.Delay(10000) a better solution?)
Thanks a lot!
If you need to use the UI you could use the example of DaveDev, otherwise the example below would also work. If you want to use UI in this example you have to use the Invoke or BeginInvoke methods of the controls.
using System;
using System.Threading;
class TimerExample
{
static void Main()
{
// Create a timer that signals the delegate to invoke
// CheckStatus after one second, and every 1/4 second
// thereafter.
Timer stateTimer = new Timer(CheckStatus);
// Change the period to every 1/2 second.
stateTimer.Change(0, 500);
}
public static void CheckStatus(Object stateInfo) {
...
}
}
I think it is important to know why not to use Thread.Sleep in this case. If you use sleep it locks up the thread. If you use a timer then the thread can be used to do other tasks in the meantime.
_timer = new DispatcherTimer();
_timer.Tick += timer_Tick;
_timer.Interval = new TimeSpan(0, 0, 0, 1);
_timer.Start();
private void timer_Tick(object sender, EventArgs e)
{
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (s, a) =>
{
//do your stuff
};
backgroundWorker.RunWorkerAsync();
}

Timer doesn't want to start again after it was disabled

I am writing a simple C# program that attempts to do something every x amount of seconds using System.Forms.Timer
The tick event calls a method that starts a new thread and disables the timer, then when the thread is done with its work, it enables the timer again, but the problem is, now it doesn't tick after it's been enabled.
static System.Windows.Forms.Timer testtimer = new System.Windows.Forms.Timer();
static void Main()
{
testtimer.Tick += testtimertick;
testtimer.Interval = 5000;
testtimer.Enabled = true;
testtimer.Start();
while (true)
{
Application.DoEvents(); //Prevents application from exiting
}
}
private static void testtimertick(object sender, System.EventArgs e)
{
testtimer.Enabled = false;
Thread t = new Thread(dostuff);
t.Start();
}
private static void dostuff()
{
//Executes some code
testtimer.Enabled = true; //Re enables the timer but it doesn't work
testtimer.Start();
}
As #grzenio said, it appears that your issue has to do with the fact that you are making cross thread calls to a Windows Form Control that was created on a different thread.
If you are using .NET 4.5 (C# 5.0), I would suggest looking at the async/await keywords, a good introduction can be found at Stephen Cleary's Blog
An example of how you could use async and await with your legacy "DoStuff":
private async void _Timer_Tick(object sender, EventArgs e)
{
_Timer.Enabled = false;
await Task.Run((() => DoStuff()));
_Timer.Enabled = true;
}
Things to notice:
async was added to the Timer_Tick event's signature.
The await keyword along with Task.Run was used to asynchronously run the DoStuff.
When using these keywords, the DoStuff will be run asynchronously and once DoStuff returns, it will continue on the line after await using the context of the thread that originally called Tick.
Don't use a GUI timer without a GUI. Don't spin with DoEvents because you are burning 100% of a CPU core with that. Use a System.Threading.Timer. It will just work.
Windows Forms controls are not thread safe, you should make sure you use them on the UI thread, see e.g. C# Windows Forms Application - Updating GUI from another thread AND class?
You can use System.Threading.Timer to do what you want to do, using the Change Method to set the time and the Period, Just restart it when you finish your work.
class Program
{
static System.Threading.Timer testtimer;
static void Main(string[] args)
{
testtimer = new System.Threading.Timer(testtimertick);
testtimer.Change(5000,0);
Console.ReadLine();
}
private static void testtimertick(object sender)
{
Thread t = new Thread(dostuff);
t.Start();
}
private static void dostuff()
{
//Executes some code
Thread.Sleep(2000);
Console.WriteLine("Tick");
testtimer.Change(5000, 0);
}
}
static System.Windows.Forms.Timer testtimer = new System.Windows.Forms.Timer();
static void Main()
{
testtimer.Tick += testtimertick;
testtimer.Interval = 5000;
testtimer.Enabled = true;
while (true)
{
Application.DoEvents(); //Prevents application from exiting
}
}
private static void testtimertick(object sender, System.EventArgs e)
{
Thread t = new Thread(dostuff);
t.Start();
}
private static void dostuff()
{
testtimer.Enabled = false;
//Executes some code
testtimer.Enabled = true; //Re enables the timer but it doesn't work
testtimer.Start();
}
I had a similar issue just now. I was disabling the timer and enabling again whenever I want.
The next time when I enable, it won't work.
I tried disposing the Timer object when I want to disable and creating new instance of it each time I want to enable it. Didn't work though.
Figured out a solution then. I'm removing the event which is configured in testtimer.Tick, and then adding it back when I want to enable the timer.
So the timer internally will be always instantiated with valid values and have its property Enabled = true. The only difference is that it won't have anything actually to perform whenever a tick event triggers.
This would imitate disabling and enabling the timer and makes it working as good as you control like Enabled = false / true.
If you really want to stick to the GUI timer, and start it from non UI thread, you can try to do similar stuff, then write to GUI from non UI thread.
Not the ideal solution, I know.
this.Invoke((MethodInvoker)delegate
{
refreshTimer.Enabled = true;
refreshTimer.Start();
});

Using Timer to delay an operation a few seconds

I am trying to delay my method by using a timer:
private System.Timers.Timer _delayTimer;
private void delay()
{
_delayTimer = new System.Timers.Timer();
_delayTimer.Interval = 5000;
//_delayTimer.Enabled = true;
_delayTimer.Elapsed += _delayTimer_Elapsed;
_delayTimer.Start();
someMethod();
}
}
private void _delayTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// delay for 5 seconds
}
When i am get into delay() method i want to start the timer, than i want the 5 seconds delay and only after that i want to execute someMethod() and currently this not happen, after execute delay() the someMethod() executed without 5 seconds delay
Your current code sets up the timer and then immediately executes someMethod. Instead of this, you need to put the actual method call inside your Elapsed handler:
private void delay()
{
_delayTimer = new System.Timers.Timer();
_delayTimer.Interval = 5000;
//_delayTimer.Enabled = true;
_delayTimer.Elapsed += _delayTimer_Elapsed;
_delayTimer.Start();
}
}
private void _delayTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
someMethod();
}
And if there's nothing else you intend to do you can simply write this inline:
_delayTimer = new System.Timers.Timer();
_delayTimer.Interval = 5000;
_delayTimer.Elapsed += (o, e) => someMethod();
_delayTimer.Start();
If you're in .Net4.5(or using BCL.Async pack) you can use Task.Delay
private async void delay()
{
await Task.Delay(5000);
someMethod();
}
If you're under .Net4.5
Try the below code. I'll suggest you to use System.Threading.Timer
var timer = new System.Threading.Timer(x => someMethod(), null, 5000, System.Threading.Timeout.Infinite);\
Don't forget when you use Threading.Timer someMethod will be invoked in ThreadPool thread, If you're accessing UI you need to marshal the call to UI thread.
If you want the current thread to pause for five seconds, then call Thread.Sleep. For example:
Thread.Sleep(TimeSpan.FromSeconds(5));
DoSomething();
Use a timer if you want something to happen five seconds from now, while you're doing something else. When the timer elapses, the action will be executed on a thread pool thread.
Also, if you only want the timer to execute one time (rather than once every five seconds), be sure to set AutoReset to false.
You need to call someMethod in the timer's Elapsed handler:
private void delay()
{
_delayTimer = new System.Timers.Timer();
_delayTimer.Interval = 5000;
_delayTimer.AutoReset = false; //so that it only calls the method once
_delayTimer.Elapsed += (s,args) => someMethod();
_delayTimer.Start();
}
You could also use Task.Delay instead:
private void delay()
{
Task.Delay(5000)
.ContinueWith(t => someMethod());
}
System.Threading.Tasks.Task.Factory.StartNew(() =>
{
System.Threading.Thread.Sleep(5000);
/*
* Here Yopur code to do some method :D
* */
});

Interacting between two threads

I am working on a winform application, and my goal is to make a label on my form visible to the user, and three seconds later make the label invisible. The issue here is timing out three seconds. I honestly do not know if this was the correct solution to my problem, but I was able to make this work by creating a new thread, and having the new thread Sleep for three seconds (System.Threading.Thread.Sleep(3000)).
I can't use System.Threading.Thread.Sleep(3000) because this freezes my GUI for 3 seconds!
private void someVoid()
{
lbl_authenticationProcess.Text = "Credentials have been verified authentic...";
Thread sleepThreadStart = new Thread(new ThreadStart(newThread_restProgram));
sleepThreadStart.Start();
// Once three seconds has passed / thread has finished: lbl_authenticationProcess.Visible = false;
}
private void newThread_restProgram()
{
System.Threading.Thread.Sleep(3000);
}
So, back to my original question. How can I determine (from my main thread) when the new thread has completed, meaning three seconds has passed?
I am open to new ideas as well as I'm sure there are many.
Right now, you are blocking the entire UI thread in order to hide a label after 3 seconds. If that's what you want, then just user Thread.Sleep(3000) from within the form. If not, though, then you're best off using a Timer:
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Interval = 3000;
timer.Tick += (s, e) => { this.lbl_authenticationProcess.Visible = false; timer.Stop(); }
timer.Start();
After 3 seconds, the label will disappear. While you're waiting for that, though, a user can still interact with your application.
Note that you must use the Forms version of Timer, since its Tick event is raised on the UI thread, allowing direct access to the control. Other timers can work, but interaction with the control would have to be Invoke/BeginInvoked.
Did you try to use Timer
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 3000;
t.Start();
t.Tick += new EventHandler(t_Tick);
void t_Tick(object sender, EventArgs e)
{
label.Visible = false;
}
You really don't need to synchronize anything. You just need a new thread, with a reference to your label. Your code is actually pretty close:
private void someVoid()
{
lbl_authenticationProcess.Text = "Credentials have been verified authentic...";
lbl_authenticationProcess.Visible = true;
Thread sleepThreadStart = new Thread(new ThreadStart(newThread_restProgram));
sleepThreadStart.Start();
}
private void newThread_restProgram()
{
System.Threading.Thread.Sleep(3000);
if (lbl_authenticationProcess.InvokeRequired) {
lbl_authenticationProcess.Invoke(new SimpleCallBack(makeInvisible));
} else {
makeInvisible();
}
}
private void makeInvisible()
{
lbl_authenticationProcess.Visible = false;
}
So, when someVoid() is called, the message on the label is set, the label is made visible. Then a new thread is started with the newThread_restProgram() as the body. The new thread will sleep for 3 seconds (allowing other parts of the program to run), then the sleep ends and the label is made invisible. The new thread ends automatically because it's body method returns.
You can make a method like so:
public void SetLbl(string txt)
{
Invoke((Action)(lbl_authenticationProcess.Text = txt));
}
And you would be able to call it from the second thread, but it invokes on the main thread.
If you're using .NET 3.5 or older, it's kinda a pain:
private void YourMethod()
{
someLabel.BeginInvoke(() =>
{
someLabel.Text = "Something Else";
Thread thread = new Thread(() =>
{
Thread.Sleep(3000);
someLabel.BeginInvoke(() => { someLabel.Visible = false; });
});
thread.Start();
});
}
That should stop you from blocking the UI.
If you're using .NET 4+:
Task.Factory.StartNew(() =>
{
someLabel.BeginInvoke(() => { someLabel.Text = "Something" });
}).ContinueWith(() =>
{
Thread.Sleep(3000);
someLabel.BeginInvoke(() => { someLabel.Visible = false; });
});
If you are willing to download the Async CTP then you could use this really elegant solution which requires the new async and await keywords.1
private void async YourButton_Click(object sender, EventArgs args)
{
// Do authentication stuff here.
lbl_authenticationProcess.Text = "Credentials have been verified authentic...";
await Task.Delay(3000); // TaskEx.Delay in CTP
lbl_authenticationProcess.Visible = false;
}
1Note that the Async CTP uses TaskEx instead of Task.
You can use an AutoResetEvent for your thread synchronization. You set the event to signalled when your secondary thread has woken from it's sleep, so that it can notify your main thread.
That means though that your main thread waits for the other thread to complete.
On that note, you can use SecondThread.Join() to wait for it to complete in your main thread.
You do either of the above, but you don't need to do both.
As suggested in the comments, having a UI thread sleep is not generally a good idea, as it causes unresponsiveness for the user.
However if you do that, you might as well just sleep your main thread and get rid of the extraneous need of the second thread.
I'm not exactly sure this is the right way to do it, but to answer your question, you have to use the Join() function.
public void CallingThread()
{
Thread t = new Thread(myWorkerThread);
t.Join();
}
public void WorkerThread()
{
//Do some stuff
}
You can also add a timeout as parameter to the function, but you don't need that here.

Categories