I wish my method to wait about 500 ms and then check if some flag has changed. How to complete this without blocking the rest of my application?
You can use await Task.Delay(500); without blocking the thread like Sleep does, and with a lot less code than a Timer.
Thread.Sleep(500) will force the current thread to wait 500ms. It works, but it's not what you want if your entire application is running on one thread.
In that case, you'll want to use a Timer, like so:
using System.Timers;
void Main()
{
Timer t = new Timer();
t.Interval = 500; // In milliseconds
t.AutoReset = false; // Stops it from repeating
t.Elapsed += new ElapsedEventHandler(TimerElapsed);
t.Start();
}
void TimerElapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Hello, world!");
}
You can set AutoReset to true (or not set it at all) if you want the timer to repeat itself.
I don't really understand the question.
If you want to block before checking, use Thread.Sleep(500);
If you want to check asynchronously every x seconds, you can use a Timer to execute a handler every x milliseconds.
This will not block your current thread.
It the method in question is executing on a different thread than the rest of your application, then do the following:
Thread.Sleep(500);
System.Threading.Thread.Sleep(500);
Update
This won't block the rest of your application, just the thread that is running your method.
Using a timer should do the trick
if you need to use a thread then here is an example
void Main()
{
System.Threading.Thread check= new System.Threading.Thread(CheckMethod);
check.Start();
}
private void CheckMethod()
{
//Code
Thread.Sleep(500);
}
Asynchron Task:
var task = new Task (() => function_test()); task.Start();
public void function_test() { `Wait for 5000 miliseconds` Task.Delay(5000);` }
I've recently been struggling with the same issue where I needed an action to be run on schedule without blocking the UI.
Here's my solution:
private void Button_Click(object sender, RoutedEventArgs e)
{
RunOnSchedule(interval, cancellationToken);
}
private void RunOnSchedule(int interval, CancellationToken cancellationToken)
{
// Start the task you want to run on schedule
TaskToRunOnSchedule(args);
Task.Run(async () =>
{
// This loop checks if the task was requested to be cancelled every 1000 ms
for (int x = 0; x < interval; x+=1000)
{
if (cancellationToken.IsCancellationRequested)
{
break;
}
await Task.Delay(1000);
}
}).GetAwaiter().OnCompleted(() =>
{
// Once the task for delaying is completed, check once more if cancellation is requested, as you will reach this point regardless of if it was cancelled or not.
if (!cancellationToken.IsCancellationRequested)
{
// Run this method again
RunOnSchedule(interval, cancellationToken);
}
});
}
In a WinForms application, when I want to wait on the main thread without blocking the app, I usually use
private void Wait (double milliseconds)
{
DateTime next = System.DateTime.Now.AddMilliseconds(milliseconds);
while (next > System.DateTime.Now)
Application.DoEvents();
}
Related
I'm unsure how best to cancel a task that is running a system timer.
In the code below, every 60 mins the timer will elapse and then run another method (CheckFileOverflow) that is used to check the file size of a system log txt. file
Cancellation of the timer ideally would be done by a button click or another method that calls the cancellation. The timer will effectively be allowed to run for as long as the software is running, but when the user eventually shuts down the software i'd like to be able to cancel the task in a responsible fashion i.e. not run the risk of ongoing thread pool resources lingering being used in the background.
I have spent many many hours reading up on cancellation tokens but still don't get it :(
public void SystemEventLoggerTimer()
{
SysEvntLogFileChckTimerRun = true;
Task.Run(() =>
{
System.Timers.Timer timer = new System.Timers.Timer
{ Interval = 1000 * 60 * 60 };
timer.Elapsed += new ElapsedEventHandler(CheckFileOverflow);
timer.Start();
});
}
I'd suggest that you use Microsoft's Reactive Framework (aka Rx) - just NuGet System.Reactive.
Then you do this:
IDisposable subscription =
Observable
.Interval(TimeSpan.FromHours(1.0))
.Subscribe(_ => CheckFileOverflow());
When you want to cancel the subscription just call subscription.Dispose().
Rx is ideal for abstracting away timers, events, tasks, async operations, etc.
You can change your method to something like this
public void SystemEventLoggerTimer(CancellationToken cancelToken)
{
SysEvntLogFileChckTimerRun = true;
Task.Run(async () =>
{
// Keep this task alive until it is cancelled
while (!cancelToken.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromMinutes(60));
CheckFileOverflow();
}
});
}
Then you call SystemEventLoggerTimer like this
var cancelSource = new CancellationTokenSource();
SystemEventLoggerTimer(cancelSource.Token);
you can cancel this Token when program has been disposed or simply at the end of your main function
Why not just have a timer accessible in the calling context (or globally in your class/application) - you'd have to do that with the CancellationTokenSource anyway! This doesn't look like the right use case for a Task.
Try this:
public void SystemEventLoggerTimer(System.Timers.Timer timer)
{
SysEvntLogFileChckTimerRun = true;
timer.Elapsed += new ElapsedEventHandler(CheckFileOverflow);
timer.Start();
}
Calling code:
var timer = new System.Timers.Timer() { Interval = 1000 * 60 * 60 };
SystemEventLoggerTimer(timer);
Cancellation code (in cancel button's event handler, etc):
timer.Stop();
I have posted below what appears to be a satisfactory solution which worked for me. Hopefully I'm responding to the thread in the correct manner... (a newbie to stackOverflow)
I setup a quick windows form for testing, I created 2qty buttons and 1qty textbox.
Buttons are used to Start & Stop the timer (using cancellation token)
The textbox is used to monitor the timer which will update with "Timer Running" message every 2 seconds. Hope this helps anyone else looking at a similar scenario...
enter image description here
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private CancellationTokenSource cancelSource;
// Button is used to START the timer.
private void TimerStartButton_Click(object sender, EventArgs e)
{
cancelSource = new CancellationTokenSource();
// Run the below method that will initiate timer to start running from
// the button click.
SystemEventLoggerTimer(cancelSource.Token);
}
private void SystemEventLoggerTimer(CancellationToken cancelToken)
{
Task.Run(async () =>
{
// Keep this task alive until it is cancelled
while (!cancelToken.IsCancellationRequested)
{
// Encapsulating the function Task.Delay with 'cancelToken'
// allows us to stop the Task.Delay during mid cycle.
// For testing purposes, have reduced the time interval to 2 secs.
await Task.Delay(TimeSpan.FromSeconds(2), cancelToken);
// Run the below method every 2 seconds.
CheckFileOverflow();
}
});
}
// When the below method runs every 2 secs, the UpdateUI will allow
// us to modify the textbox form controls from another thread.
private void CheckFileOverflow()
{
UpdateTextbox("Timer Running");
}
// UpdateUI will allow us to modify the textbox form controls from another thread.
private void UpdateTextbox(string s)
{
Func<int> del = delegate ()
{
textBox1.AppendText(s + Environment.NewLine);
return 0;
};
Invoke(del);
}
// Button that is used to STOP the timer running.
private void TimerStopButton_Click(object sender, EventArgs e)
{
// Initiate the cancelleation request to method "SystemEventLoggerTimer"
cancelSource.Cancel();
}
}
I am making a small game with an auto play feature, but the program runs too fast so the user can't see the outcome at each stage. I am using VS 2017, so I can't use async (at least from what I have read). How can I have the program wait and allow the UI to update?
I am working in a do while loop. The main chunk of the game executes, updates the UI, and then waits for the player to click a button (assuming auto play is not running), with auto play running the do while loop repeats, but after the UI updates it would wait X seconds.
Use a Timer component instead of a loop, and put the loop body in the timer's Elapsed event.
And VS2017 definitely supports async, but it wouldn't help in this case... things would still move too fast for the user.
You can use async/await to slow down the execution of event handler without having to split the logic. This is pretty simple:
async void Button_Click(object sender, RoutedEventArgs e) // wpf event handler
{
...
await Task.Delay(1000); // pause 1 second
...
while (someCondition)
{
...
await Task.Delay(1000);
...
}
}
You can read about async/await at msdn.
If you are using WPF, then you have to look into animations. They are much simpler to use to ensure smooth changes than manually changing something (position, sizes).
Usage: DelayFactory.DelayAction(500, new Action(() => { this.RunAction(); }));`
//Note Forms.Timer and Timer() have similar implementations.
//Assumes you will have a DelayFactory Static Class
public static void DelayAction(int millisecond, Action action)
{
var timer = new DispatcherTimer();
timer.Tick += delegate
{
action.Invoke();
timer.Stop();
};
timer.Interval = TimeSpan.FromMilliseconds(millisecond);
timer.Start();
}
Wait function using timers, no UI locks.
public void wait(int milliseconds)
{
System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
if (milliseconds == 0 || milliseconds < 0) return;
//Console.WriteLine("start wait timer");
timer1.Interval = milliseconds;
timer1.Enabled = true;
timer1.Start();
timer1.Tick += (s, e) =>
{
timer1.Enabled = false;
timer1.Stop();
//Console.WriteLine("stop wait timer");
};
while (timer1.Enabled)
{
Application.DoEvents();
}
}
Usage:
wait(1000); //wait one second
It looks like you have a couple of options
1.You can try Sleep -(but it may hang the UI)
int Seconds = 1;
Threading.Thread.Sleep(Seconds * 1000);
2.You can try this code:
int Seconds = 1;
Private void WaitNSeconds(int seconds)
{
if (seconds < 1) return;
DateTime _desired = DateTime.Now.AddSeconds(seconds);
while (DateTime.Now < _desired) {
System.Windows.Forms.Application.DoEvents();
}
}
3.Try to use Async and see what happens
async Task MakeDelay() {
await Task.Delay(5000);
}
private async void btnTaskDelay_Click(object sender, EventArgs e) {
await MakeDelay();
}
I was putting together a small little demo to take a long running method simulated with a Thread.Sleep() and wanted to add async to easily go from a synchronous process to an async one. Here's the initial code:
private void button1_Click(object sender, EventArgs e)
{
LongProcess();
}
private void LongProcess()
{
for (int i = 0; i < 33; i++)
{
progressBar1.Value += 3;
Thread.Sleep(1000);
}
progressBar1.Value += 1;
}
I was thinking I could simply change the Thread.Sleep(1000) into a new Task(()=>Thread.Sleep(1000)), like so:
private void button1_Click(object sender, EventArgs e)
{
LongProcess();
}
private async void LongProcess()
{
for (int i = 0; i < 33; i++)
{
progressBar1.Value += 3;
await new Task(()=>Thread.Sleep(1000));
}
progressBar1.Value += 1;
}
However this never returns to the loop after the first await. If I change the Thread.Sleep to a Task.Delay everything works, but I don't understand why my code doesn't work. I assume something is getting blocked forever, but it doesn't quite make sense. Can anyone explain how my code works, and a possible solution without changing to Task.Delay (just so I can get another perspective of how this works)?
Task.Delay isn't same as staring a Task with Thread.Sleep. Task.Delay uses Timer internally and thus it doesn't blocks any thread, however starting a new Task with Thread.Sleep blocks the thread (typically Threadpool thread).
In your example you never started the Task. Creating a Task with constructor will return a Unstarted task needs to be started with a call to Start method. Otherwise it will never complete(because you never started it).
However calling Task.Start is discouraged, You can call Task.Factory.StartNew(()=> Thread.Sleep(1000)) or Task.Run(()=> Thread.Sleep(1000)) if you want to waste a resource.
Also, be aware that StartNew is dangerous, you should prefer Task.Run over StartNew unless there's a compelling reason to do so.
new Task(()=>Thread.Sleep(1000)) creates a Task, but doesn't start it.
You can use Task.Run(() => Thread.Sleep(1000)) or Task.Factory.StartNew(() => Thread.Sleep(1000)) to create and start a task.
To answer the question title - Task.Delay is cancellable!
Consider a popular implementation using TaskCompletionSource.
static Task Delay(int delayTime, System.Threading.CancellationToken token)
{
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
if (delayTime < 0) throw new ArgumentOutOfRangeException("Delay time cannot be under 0");
System.Threading.Timer timer = null;
timer = new System.Threading.Timer(p =>
{
timer.Dispose(); //stop the timer
tcs.TrySetResult(null); //timer expired, attempt to move task to the completed state.
}, null, delayTime, System.Threading.Timeout.Infinite);
token.Register(() =>
{
timer.Dispose(); //stop the timer
tcs.TrySetCanceled(); //attempt to mode task to canceled state
});
return tcs.Task;
}
You cannot do this with Thread.Sleep. You can do it with a big old loop but that simply emulates the underlying Timer in the code above.
I have a WinForms application that consists of a main UI thread and 4 tasks. My main form has a private member level variable like this:
private bool keepThreadsRunning = false;
In the Load() event of my main form, I have the following:
keepThreadsRunning = true;
var task1Worker = Task.Factory.StartNew(() => DoStuff1());
var task2Worker = Task.Factory.StartNew(() => DoStuff2());
var task3Worker = Task.Factory.StartNew(() => DoStuff3());
var task4Worker = Task.Factory.StartNew(() => DoStuff4());
Inside of each of my DoStuff() methods, I basically have this:
while (keepThreadsRunning)
{
// do work here
Thread.Sleep(30000); // a couple of my tasks only need to run every 30 seconds or so
}
Lastly, in my Form_Closing() event handler, I have the following:
keepThreadsRunning = false;
this.Close();
Watching my application in task manager, it appears that the process is ending when I close my form but I'm a little confused about the four tasks. Is my call to this.Close() really causing those tasks to terminate (even if they're in the Thread.Sleep() call when it happens)? And is there a better way of accomplishing this than the way I'm coding it right now?
EDIT - I've looked briefly at task cancellation (when my app exits) but my understanding is that my tasks would need to periodically check the cancellation token to determine if they've been cancelled. Given that some of my tasks need to run every 30 seconds, I couldn't figure out how I'd implement that 30s wait (currently a Thread.Sleep()) and still have the task be checking the cancellation token.
Rather than using a boolean and Thread.Sleep(), use a WaitHandle, specifically a ManualResetEvent, created like this:
var threadTerminationHandle = new ManualResetEvent(false);
In your thread:
do {
// do work here
} while (!threadTerminationHandle.WaitOne(TimeSpan.FromSeconds(30))
This will wait until the WaitHandle is set, or 30 seconds elapses, whichever is sooner.
In your form:
threadTerminationHandle.Set();
Close();
First of all, closing the main UI thread will terminate your other tasks. If you need them to keep running, maybe consider running them in a seperate Console Application, or a Windows Service.
Even if you found a way to delay the closing of the form while you finish running the methods you need to run, this would only work if the end user closed the form in the way you wanted, and Windows being Windows there are a million and one ways to close an application so there is no guarantee that this will work.
For running a method asynchronously every x amount of seconds, you could just use a timer for the whole thing, like so:
using System;
using System.Timers;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var timer1 = new System.Timers.Timer { Interval = 30000, Enabled = true };
var timer2 = new System.Timers.Timer { Interval = 20000, Enabled = true };
var timer3 = new System.Timers.Timer { Interval = 10000, Enabled = true };
var timer4 = new System.Timers.Timer { Interval = 5000, Enabled = true };
timer1.Elapsed += timer1_Elapsed;
timer2.Elapsed += timer2_Elapsed;
timer3.Elapsed += timer3_Elapsed;
timer4.Elapsed += timer4_Elapsed;
}
void timer4_Elapsed(object sender, ElapsedEventArgs e)
{
//do work here
}
void timer3_Elapsed(object sender, ElapsedEventArgs e)
{
//do work here
}
void timer2_Elapsed(object sender, ElapsedEventArgs e)
{
//do work here
}
void timer1_Elapsed(object sender, ElapsedEventArgs e)
{
//do work here
}
}
}
When you close application, tasks will be closed accordingly because task is processed under background thread from thread pool. So, you don't need to periodically check the cancellation token to determine if they've been cancelled
I know how to start a function in x seconds, its something like this:
private Timer timer1;
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 2000; // in miliseconds
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
function1();
function2();
function3();
}
The problem here: The functions cannot run at the same time. Function2 can only run if Function1 is done. But I want them running at the same time. Thats why I could do this:
private void timer1_Tick(object sender, EventArgs e)
{
Parallel.Invoke(
() => Function1(),
() => Function2(),
() => Function3()
);
}
Is this the smartest way to do it in c#? What I dont understand with Parallel.Invoke: what if my timer is set for 5 sec and after 5 sec function1,2 and 3 are not done but I call them all again. Do I start these functions in a new thread? Are there after some calls x-threads running function1() (at the same time)? Wondering is that really healthy.
If somebody would like to get more information: function1 is just there to copy file x from folder a to b, function2 is only there to read all files from folder b and save the information and function3 is only there to check the connection and if there is a connection send the appropriate file to somebody.
Any suggestions to the code? Thank you
Parallel.Invoke runs all your functions in parallel. Since function2 shouldn't run before function1, create a task that runs them in background but sequentially.
Task.Factory.StartNew(() =>
{
function1();
function2();
function3();
});
what if my timer is set for 5 sec and after 5 sec function1,2 and 3 are not done
you can use a bool to see whether they are completed or not.
Use System.Threading.Timer to schedule the callback on a ThreadPool thread, so you don't need to create a new task. It also allows you to control the intervals to prevent the overlap of callbacks.
// fired after 5 secs, but just once.
_timer = new System.Threading.Timer(Callback, null, 5000, Timeout.Infinite);
// on the callback you must re-schedule the next callback time;
private void Callback(Object state) {
Function1();
Function2();
// schedule the next callback time
_timer.Change(5000, Timeout.Infinite);
}
Have you looked at Tasks?
http://msdn.microsoft.com/en-us/library/dd537610
You could do something like this:
Task[] tasks = new Task[3];
tasks[0] = Task.Factory.StartNew(() => Function1());
tasks[1] = Task.Factory.StartNew(() => Function2());
tasks[2] = Task.Factory.StartNew(() => Function3());
Task.WaitAll(tasks);
The above will allow you to run the functions in parallel, which is what you imply you want.
If you don't want to block inside the timer1_Tick waiting for all the Tasks to complete, then don't use WaitAll....instead you could check if the Tasks have completed by checking IsCompleted on the Tasks when your timer gets fires again....then decide whether to issue the next batch of functions.