Reputation: 39
I use Thread.sleep() in my application and it works good. But it hangs my whole user interface until the sleeping time is finished. This kind of hang also found when I refresh any text of a label continuously.
do
{
lbl_waiting.Text = "Waiting for 20 seconds..";
Thread.Sleep(1000 * 60); //// 60 seconds waiting time
string resultFromApi = SMS.OneToOneBulk(messageHeader, SMS_number_list);
} while(myCondition);
in this waiting time my full user interface gets hang. I need to work this process without interrupting my frontEnd or user interface.
Upvotes: 0
Views: 1482
Reputation: 116
If you have a look at this dispatcherTimer class
you can make things trigger on a specific timed interval.
Importing
using System.Windows.Threading
Then setting up the timer thread
// DispatcherTimer setup
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,0,60); // set how often to try and run
dispatcherTimer.Start();
and then define the tick function as you see fit
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
if (Conditions are met)
{
string resultFromApi = SMS.OneToOneBulk(messageHeader, SMS_number_list);
}
}
Upvotes: 0
Reputation: 176189
You can go asynchronous and use Task.Delay()
instead:
async Task MyEventHandler()
{
/// your code
/// delay execution but don't block
await Task.Delay(TimeSpan.FromSeconds(20));
}
The difference to Thread.Sleep
is that it doesn't block.
You use Thread.Sleep
when you want to block the current thread.
You use Task.Delay
when you want a logical delay without blocking the current thread.
If hanging UI is a concern you should have a look into how to use asynchronous methods and async/await in your ASP.NET application. A good starting point is this article:
Using Asynchronous Methods in ASP.NET 4.5
Upvotes: 1
Reputation: 137148
If this code is in the main application thread then it will stop the UI along with everything else.
If you need to wait between sending text messages then the sending of the messages needs to be done on a background worker thread that can be waited without blocking the UI
Upvotes: 0
Reputation: 182
You need to implement multithreading to bypass this problem, Thread.Sleep does, indeed, stop your entire application.
Upvotes: 0