Pausing appending of Text for a certain number of milliseconds - c#

I'm currently making a text based game, but I need the calls to pause for a certain number of milliseconds. I'm looking for something like this:
void InitProgram()
{
WriteToText("Welcome!");
CreatePause(3000); // Pause execution HERE for 3 seconds without locking UI
WriteToText("How are you?"); // Continue
StartTutorial();
}
So like, the method will be called, do its waiting thing, and then return. And when it returns, normal execution is continued.
What can I do for this effect?

You could use a timer:
readonly Timer _timer = new Timer();
void InitProgram()
{
WriteToText("Welcome!");
_timer.Interval = 3000;
_timer.Tick += timer_Tick;
_timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
WriteToText("How are you?"); // Continue
StartTutorial();
_timer.Stop();
}
If you wanted to call this multiple times, just put _timer.Start into it's own method, every time you call it, 3 seconds later whatever is in timer_Tick will happen:
private void StartTimer()
{
_timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
WriteToText("How are you?"); // Continue
StartTutorial();
_timer.Stop();
}

If target framework is 4.0 or higher and IDE is VS2012 or higher, then you can use async/await
private async void Foo()
{
Console.WriteLine("Going to Await");
await Task.Delay(5000);
Console.WriteLine("Done with awaiting");
}
It's pretty simple and straightforward and the biggest advantage is, that your "linear" flow is kept, because the necessary callbacks etc are handled by the compiler automatically.

How about something like this?
Its all pseudo code, I have not tested...
Thread _thread;
void InitProgram()
{
WriteToText("Welcome!");
ThreadStart ts = new ThreadStart(StartThread);
_thread = new Thread(ts);
_thread.Start();
}
private void StartThread()
{
Thread.CurrentThread.Sleep(3000);
this.Invoke(delegate { this.StartTutorial(); });
}
private void StartTutorial()
{
WriteToText("How are you?"); // Continue
//Start tutorial
}

Hahahahhaha! I figured out the answer using possibly the most crazy method available! Check this out, guys!
First, declare global List:
private List<Action> actionList = new List<Action>();
Now, this is what you do in the method you wish to call wait from:
WriteToLog("Hello!");
Action act = delegate() { WriteToLog("How are you?"); }; actionList.Add(act); // Create a new Action out of this method and add it to the action list!
CreatePause(3000); // Call the method with your specified time
void CreatePause(int millisecondsToPause)
{
Action w = delegate() { Thread.Sleep(millisecondsToPause); };
for (int i = 0; i < actionList.Count; i++) // Iterate through each method in the action list that requires attention
{
Action a_Instance = (Action)actionList[i]; // Add a cast to each iteration
AsyncCallback cb = delegate(IAsyncResult ar) { Invoke(a_Instance); w.EndInvoke(ar); }; // Do each method!!!!
w.BeginInvoke(cb, null);
}
actionList.Clear(); // Clear that list!
return; // Return!
}
To be honest, this shouldn't work, but it does.

Related

How to have program wait X seconds and allow UI to execute?

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();
}

How do I make a repeating button with a thread in c#?

I've looked at some guides and none of them have gotten me all the way there. I've never made a thread, discussed a thread, or seen a thread at the grocery store, so this may be a problem. Currently. I'm trying:
private void btnHUp_MouseDown(object sender, MouseEventArgs e)
{
{
ThreadStart HUp = new ThreadStart(dothis);
t = new Thread(HUp);
t.Start();
}
}
public void dothis()
{
if (intHour < 23)
intHour = intHour += intStep;
lblTimerHour.Text = intHour.ToString("00");
}
private void btnHUp_MouseUp(object sender, MouseEventArgs e)
{
t.Abort();
}
}
That gets me InvalidOperationException was unhandled on the
lblTimerHour.Text = intHour.ToString("00");
line. I read what that means and... it might as well be in Mandarin, I kind of get the general concept-ish of what's going wrong, but it's painfully fuzzy. If you asked me the first step in fixing it I'd look at you like a deer in the headlights. We just haven't gotten that far in my class yet.
The problem here is that the label you are trying to update is owned by the main thread (i.e. what the UI runs on), and that means that only that thread can access/update it. So, since you are in a different thread, you need to tell the UI thread to update the label for you.
Something like this would work:
Action updateLabel = () => lblTimerHour.Text = intHour.ToString("00");
lblTimerHour.BeginInvoke(updateLabel);
What this does is tell the lblTimerHour to invoke the action you define above (updateLabel).
See this post: How to update the GUI from another thread in C#?
lblTimerHour.Invoke((MethodInvoker)delegate {
//Do what you need to do with the label
lblTimerHour.Text = intHour.ToString("00");
});
Edit
This should do the trick:
public void dothis()
{
do
{
if (intHour < 23)
intHour = intHour += intStep;
lblTimerHour.Invoke((MethodInvoker)delegate {
//Update the label from the GUI thread
lblTimerHour.Text = intHour.ToString("00");
});
//Pause 1 sec. Won't freeze the gui since it's in another thread
System.Thread.Sleep(1000);
}while(true); //Thread is killed on mouse up
}
Well, let's take a look and see what you already have.
First, I see you did this.
private void btnHUp_MouseDown(object sender, MouseEventArgs e)
{
ThreadStart HUp = new ThreadStart(dothis);
t = new Thread(HUp);
t.Start();
}
While this certainly is not the freshest stuff around it will still work. If you wanted some fresher ingredients then you might go with this instead.
private void btnHUp_MouseDown(object sender, MouseEventArgs e)
{
Task.Factory.StartNew(dothis);
}
Second, I see this.
public void dothis()
{
if (intHour < 23) intHour = intHour += intStep;
lblTimerHour.Text = intHour.ToString("00");
}
The problem here is that you are attempting to update a UI control from a thread other than the main UI thread. You see UI controls have what is called thread affinity. They can only ever be accessed from the thread that created them. What you have will lead to all kinds of unpredictable problems up to and including tearing a whole in spacetime.
A better option would be to do this.
public void dothis()
{
while (intHour < 23)
{
intHour = intHour += intStep;
lblTimerHour.Invoke((Action)(
() =>
{
lblTimerHour.Text = intHour.ToString("00");
}));
}
}
I assumed that you were missing the loop so I added it. While I cannot say that I personally have a taste for this kind of thing it is much easier to swallow. The real problem here is that the worker thread really does not do a whole lot of useful work. And then to top it off we have to use an awkward marshaling operation to transfer the result back to the UI thread. It is not pretty, but it will work.
And finally that brings me to this.
private void btnHUp_MouseUp(object sender, MouseEventArgs e)
{
t.Abort();
}
You are attempting to abort a thread which is highly inadvisable. The problem is that it yanks control from the thread at unpredictable times. That thread might be in the middle of a write to data structure which would corrupt it. This is actually a pretty bad problem because any data structure in the process of being manipulated from any one of the frames on the call stack could be in an inconsistent state. This includes code you did not write. That is why it is hard to say what you may or may not be corrupting by doing this.
What you need to consider instead is using the cooperative cancellation mechanisms. This includes the use of CancellationTokenSource and CancellationToken. Here is how it might look once we put everything together.
private CancellationTokenSource cts = null;
private void btnHUp_MouseDown(object sender, MouseEventArgs e)
{
cts = new CancellationTokenSource();
Task.Factory.StartNew(() => dothis(cts.Token));
}
private void btnHUp_MouseUp(object sender, MouseEventArgs e)
{
cts.Cancel();
}
public void dothis(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
intHour += intStep;
lblTimerHour.Invoke((Action)(
() =>
{
lblTimerHour.Text = intHour.ToString("00");
}));
Thread.Sleep(1000);
}
}
What this does is signal that the worker thread should gracefully shutdown on its own. This gives the worker thread a chance to tidy things up before eventually terminating itself.
If you want to update the UI every X period of time then there are already existing tools for this; a Timer will do exactly what you want, and it will be much more efficient and easier to code than creating a new thread that just spends most of its time napping. Additionally, aborting threads is a very bad sign to see. Avoid it at all costs.
First create the timer and configure it in the constructor:
private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
private int hour = 0;
private int step = 0;
public Form1()
{
InitializeComponent();
timer.Tick += timer_Tick;
timer.Interval = 1000;
}
Have the Tick event do whatever should be done whenever it ticks.
private void timer_Tick(object sender, EventArgs e)
{
if (hour < 23)
{
hour += step;
lblTimerHour.Text = hour.ToString("00");
}
}
Then just start the timer when you want it to start ticking and stop the timer when you want it to stop:
private void btnHUp_MouseDown(object sender, MouseEventArgs e)
{
timer.Start();
}
private void btnHUp_MouseUp(object sender, MouseEventArgs e)
{
timer.Stop();
}
The timer will automatically ensure that the Tick event handler runs in the UI thread, and it won't block the UI thread (or any other thread) when its waiting for the next event to happen, it will just do nothing.

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
* */
});

How to display the time elapsed in a label

What should be straight forward is not here and I couldnt find a way yet in spite of reading a lot.
I have a button which executes a time consuming function. So on clicking the button should show time elapsed in milliseconds in a label with an interval of 500 ms. And when the desired result is achieved I want the timer to stop. I dont just need the final time (the total time consumed) in a label, but the label should dynamically show the time being elapsed. My code would be:
private void btnHistory_Click(object sender, EventArgs e)
{
Class1 c = new Class1();
c.StartClock(ref label12);
Utility.PopulateHistory(dgvRecords_history, _util); //time consuming function
c.StopClock();
}
And in Class1 I write this:
internal void StartClock(ref Label l)
{
Timer t = new Timer();
t.Interval = 500;
t.Enabled = true;
t.Tag = l;
t.Tick += new EventHandler(t_Tick);
t.Start();
}
int i;
bool stop;
void t_Tick(object sender, EventArgs e)
{
if (stop)
{
((Timer)sender).Stop();
return;
}
((Label)((Timer)sender).Tag).Text = (++i).ToString();
}
internal void StopClock()
{
i = 0;
stop = true;
}
What happens is, the t_Tick event is fired only after the complete code under button event is fired. That is the tick event is fired after it goes through the StopClock function! I got no idea why on earth it should be that!
2 questions basically:
How can my requirement be achieved in the right way to handle these? I know I should use other built in classes to evaluate performance, but this is just for display purpose. For this, what is the ideal approach?
Why is my code not working?
EDIT: I have used here System.Windows.Forms Timer here, but the result is not any different with System.Timers Timer
The problem is that your long-running task is also running on the UI thread. So the timer can't fire and update the UI, since the thread is busy handling the long-running task.
Instead, you should use a BackgroundWorker to handle the long-running task.
In code:
private void btnHistory_Click(object sender, EventArgs e)
{
Class1 c = new Class1(ref label12);
c.StartClock();
var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (s, e) =>
{
// time consuming function
Utility.PopulateHistory(dgvRecords_history, _util);
};
backgroundWorker.RunWorkerCompleted += (s, e) =>
{
c.StopClock();
};
backgroundWorker.RunWorkerAsync();
}
As ChrisWue noted, since you now have the long-running task in a separate thread, it needs to invoke any access to the UI controls on the UI thread.
If your long-running task just needs some data from the UI to start, you can pass that data as parameter of RunWorkerAsync(). If you need to output some result data to the UI, you can do that in the handler of the RunWorkerCompleted event. If you occasionally need to update the UI as progress is being made, you can do that in the handler of the ProgressChanged event, calling ReportProgress() in your DoWork handler.
If none of the above are needed, you could use the ThreadPool, as in StaWho's answer.
Your time consuming function is blocking the main thread. You can use BackgroundWorker or below trick:
public Form1()
{
InitializeComponent();
t.Tick +=new EventHandler(t_Tick);
t.Interval = 500;
}
int timeElapsed = 0;
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
private void button1_Click(object sender, EventArgs e)
{
t.Start();
ThreadPool.QueueUserWorkItem((x) =>
{
TimeConsumingFunction();
});
}
void TimeConsumingFunction()
{
Thread.Sleep(10000);
t.Stop();
}
void t_Tick(object sender, EventArgs e)
{
timeElapsed += t.Interval;
label1.Text = timeElapsed.ToString();
}
Add the timer to the Components collection of the form. Or store the timer in a field in the class.
The timer is garbage collected because it is not longer reachable when your method returns.
I don't know about your long running code, but out should new run on a separate thread, or make calls to Application.DoEvents
(And remove the ref in your code, it is not used).
#Dainel Rose's answer worked for me perfectly, but only if invalid cross thread operation is handled. I could do so like:
private void btnHistory_Click(object sender, EventArgs e)
{
Class1 c = new Class1(ref label12);
c.StartClock();
var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += ((s, e) =>
{
// time consuming function
Utility.PopulateHistory(dgvRecords_history, _util);
});
backgroundWorker.RunWorkerCompleted += ((s, e) =>
{
c.StopClock();
});
backgroundWorker.RunWorkerAsync();
}
And in the Utility class where the time consuming function runs,
internal static void PopulateHistory(DataGridView dgv, Utility util)
{
SetDataGridView_History(dgv, util);
}
delegate void UpdateDataGridView_History(DataGridView dgv, Utility util);
static void SetDataGridView_History(DataGridView dgv, Utility util)
{
if (dgv.InvokeRequired)
{
UpdateDataGridView_History updaterDelegate = new UpdateDataGridView_History(SetDataGridView_History);
((Form)util._w).Invoke(updaterDelegate, new object[] { dgv, util });
}
else
//code that utilizes UI thread (long running process in my case)
}
Thanks all who helped. I'm marking Daniel's answer..

timer inside thread

My Aim: I am having a credit card wait window. I will call a function from the client to wait for the credit card swipe. In order to avoid the program getting stuck while waiting for the credit card . I am using a delegate to run a timer. The delegate will call a timer. The timer periodically checks for the presence for the card. If it found a card it will a callback/delegate assigned by the client.
the code is given below, my questions are
1) Will the _timer_Elapsed will get called within the thread so that it will add minimum overhead to the ui window?
2) How can i call the callback/event of the base class from the timer function. I have written a protected method which will call the event/delegate in the base class. I need to call the protected method from the timer function( which is inside a delegate in the derived class.)?
Wait wait = delegate()
{
_timer = new Timer(3000); // Set up the timer for 3 seconds
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
_timer.Enabled = true; // Enable it
static void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
// if(CheckCardsPresence())
{
//RaiseEvent()
//KillTimer()
}
//else
{
// do nothing. wait more
}
}
};
wait.Invoke();
No, the timer callback will not execute on the delegate-thread.
How could it? A timer cannot 'break in' on a thread, that thread has to poll.
This delegate-thread will terminate immediately after starting the timer. Which means you don't need this thread at all. Unless there is code not shown.
When you use a System.Threading.Timer the callback will be pushed onto the Threadpool.
To the second question (do try to ask only 1 question at a time)
A protected member should be accessible from an anonymous (embedded) method. Do you have a concrete problem?
From the MSDN documentation (sorry I got the wrong class the first time around)
This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. It requires that the user code have a UI message pump available.
This is a roundabout way of saying that the event will be raised on the UI thread / message pump, i.e. the answer to your first question is yes as long as by "the thread" you mean "the UI thread".
I don't really understand your second question - what base class are you talking about?
First, that code will not compile. You cannot declare a named method from within another method. You can, however, declare an anonymous method or lambda expression and then assign it to a delegate reference.
There may not be any need to do asynchronous polling of the credit card device. You might be able to use a System.Windows.Forms.Timer and perform the polling from the Tick event which runs on the UI thread. This would be acceptable if the CheckCardsPresence is a quick operation.
public class CreditCardWaitWindow : Form
{
private System.Windows.Timer timer = new System.Windows.Timer();
private void Form_Load(object sender, EventArgs args)
{
timer.Tick += OnTick;
timer.Interval = 3000;
timer.Start();
}
private void OnTick(object sender, EventArgs args)
{
if (CheckCardsPresence())
{
RaiseEvent();
timer.Stop();
}
}
}
If polling the credit card device is a time consuming operation then you will want to perform this operation on another thread to avoid blocking the UI.
public class CreditCardWaitWindow : Form
{
private System.Timers.Timer timer = new System.Timers.Timer();
private void Form_Load(object sender, EventArgs args)
{
timer.Elapsed += OnElapsed;
timer.Interval = 3000;
timer.AutoReset = false;
timer.Start();
}
private void OnElapsed(object sender, ElapsedEventArgs args)
{
if (CheckCardsPresence())
{
Invoke(
(MethodInvoker)(() =>
{
RaiseEvent();
}), null);
}
else
{
timer.Start();
}
}
}
Here is a cleaner implementation using a Task.
public class CreditCardWaitWindow : Form
{
private void Form_Load(object sender, EventArgs args)
{
Task.Factory.StartNew(
() =>
{
while (true)
{
Thread.Sleep(3000);
if (CheckCardsPresence()) break;
}
}, TaskCreationOptions.LongRunning).ContinueWith(
() =>
{
RaiseEvent();
}, TaskScheduler.FromCurrentSychronizationContext());
}
}
And to really top things off you could do this in C# 5.01 with the new await keyword. I am not sure it can get anymore succinct than that!
public class CreditCardWaitWindow : Form
{
private async void Form_Load(object sender, EventArgs args)
{
while (!CheckCardsPresence()) await Task.Delay(3000);
RaiseEvent();
}
}
1C# 5.0 has not been released yet.

Categories