How do I add a delay after a count down timer - c#

I am using a DispatcherTimer to perform a count down before triggering the release on a camera. The UpdateCountdown method is used to change the image displayed to the user before the camera fires. Rather than having the TakePicture method execute immediately, I would like have a slight delay after the counter reaches zero and the last image is displayed.
The code shown below results in the pause occurring at the _countdown = 1 point. While the final image displays and TakePicture() fires almost simultaneously (I think TakePicture happens first).
_countdownTimer = new DispatcherTimer();
_countdownTimer.Interval = TimeSpan.FromSeconds(1);
_countdownTimer.Tick += new EventHandler(delegate(object s, EventArgs a)
{ UpdateCountdown(); } );
_countdownTimer.Tick += new EventHandler(delegate(object s, EventArgs a)
{if (_countdown == _countdownMax)
{
System.Threading.Thread.Sleep(2000); // Slight delay before taking picture
Camera.TakePicture();
} });
}
public void StartCountdown()
{
if (doCount)
{
doCount = false;
UpdateCountdown();
_countdownTimer.Start();
}
}
private void UpdateCountdown()
{
_countdown--;
CountdownImage = _countDownImages[_countdown]; // Data bound to Image Control
if (_countdown == 0)
{
_countdown = _countdownMax;
_countdownTimer.Stop();
doCount = true;
}
What am I not taking into account with my timing?

The UI does not update immediately when you change control properties - it only updates when the thread becomes idle (that is, after all your event handlers finish executing).
Thread.Sleep blocks the thread, the event handlers don't finish executing and UI isn't redrawn.
You have to either use another timer (start a new timer on the last tick of the existing timer and call TakePicture on teh new timer's tick) or, even better, use the last tick of the existing timer - update UI when (_countdown <= _countdownMax), take picture when (_countdown == _countdownMax + 1).

Why not just make your display always show 1 less than the number of seconds remaining. That way when you get to zero, (obviously with a Math.Max(0, _countdown) to prevent showing -1) it will seem like the time has run out even though there's one more second to go.
Edit: What I meant to imply but did not state - was that you could then just have one Tick handler and not use Sleep at all which will just wind up blocking the UI anyway which will probably block your UI from updating.

I don't think that events guarantee that event handlers are triggered in the order that they are registered. Try
_countdownTimer.Tick += new EventHandler(delegate(object s, EventArgs a)
{
UpdateCountdown();
if (_countdown == _countdownMax)
{
System.Threading.Thread.Sleep(2000); // Slight delay before taking picture
Camera.TakePicture();
}
});
}

Related

How to keep cancelling the task until a condition is met (TaskCanceledException)

I want to call a method after some delay when an event is raised, but any subsequent events should "restart" this delay. Quick example to illustrate, the view should be updated when scrollbar position changes, but only 1 second after the user has finished scrolling.
Now I can see many ways of implementing that, but the most intuitive would be to use Task.Delay + ContinueWith + cancellation token. However, I am experiencing some issues, more precisely subsequent calls to my function cause the TaskCanceledException exception and I started to wonder how I could get rid of that. Here is my code:
private CancellationTokenSource? _cts;
private async void Update()
{
_cts?.Cancel();
_cts = new();
await Task.Delay(TimeSpan.FromSeconds(1), _cts.Token)
.ContinueWith(o => Debug.WriteLine("Update now!"),
TaskContinuationOptions.OnlyOnRanToCompletion);
}
I have found a workaround that works pretty nicely, but I would like to make the first idea work.
private CancellationTokenSource? _cts;
private CancellationTokenRegistration? _cancellationTokenRegistration;
private void Update()
{
_cancellationTokenRegistration?.Unregister();
_cts = new();
_cancellationTokenRegistration = _cts.Token.Register(() => Debug.WriteLine("Update now!"));
_cts.CancelAfter(1000);
}
You should consider using Microsoft's Reactive Framework (aka Rx) - NuGet System.Reactive and add using System.Reactive.Linq;.
You didn't say hat UI you're using, so for Windows Forms also add System.Reactive.Windows.Forms and for WPF System.Reactive.Windows.Threading.
Then you can do this:
Panel panel = new Panel(); // assuming this is a scrollable control
IObservable<EventPattern<ScrollEventArgs>> query =
Observable
.FromEventPattern<ScrollEventHandler, ScrollEventArgs>(
h => panel.Scroll += h,
h => panel.Scroll -= h)
.Select(sea => Observable.Timer(TimeSpan.FromSeconds(1.0)).Select(_ => sea))
.Switch();
IDisposable subscription = query.Subscribe(sea => Console.WriteLine("Hello"));
The query is firing for every Scroll event and starts a one second timer. The Switch operator watches for every Timer produces and only connects to the latest one produced, thus ignoring the previous Scroll events.
And that's it.
After scrolling has a 1 second pause the word "Hello" is written to the console. If you begin scrolling again then after every further 1 second pause it fires again.
In my own experience I've dealt with lots of scenarios just like the one you describe, e.g. update something one second after the mouse stops moving etc.
For a long time I would do timer restarts just the way you describe, by cancelling an old task and starting a new one. But I never really liked how messy that was, so I came up with an alternative that I use in production code. Long-term it has proven quite reliable. It takes advantage of the captured context associated with a task. Multiple instances of TaskCanceledException no longer occur.
class WatchDogTimer
{
int _wdtCount = 0;
public TimeSpan Interval { get; set; } = TimeSpan.FromSeconds(1);
public void Restart(Action onRanToCompletion)
{
_wdtCount++;
var capturedCount = _wdtCount;
Task
.Delay(Interval)
.GetAwaiter()
.OnCompleted(() =>
{
// If the 'captured' localCount has not changed after awaiting the Interval,
// it indicates that no new 'bones' have been thrown during that interval.
if (capturedCount.Equals(_wdtCount))
{
onRanToCompletion();
}
});
}
}
Another nice perk is that it doesn't rely on platform timers and works just as well in iOS/Android as it does in WinForms/WPF.
For purposes of demonstration, this can be exercised in a quick console demo where the MockUpdateView() action is sent to the WDT 10 times at 500 ms intervals. It will only execute one time, 500 ms after the last restart is received.
static void Main(string[] args)
{
Console.Title = "Test WDT";
var wdt = new WatchDogTimer { Interval = TimeSpan.FromMilliseconds(500) };
Console.WriteLine(DateTime.Now.ToLongTimeString());
// "Update view 500 ms after the last restart."
for (int i = 0; i < 10; i++)
{
wdt.Restart(onRanToCompletion: ()=>MockUpdateView());
Thread.Sleep(TimeSpan.FromMilliseconds(500));
}
Console.ReadKey();
}
static void MockUpdateView()
{
Console.WriteLine($"Update now! WDT expired {DateTime.Now.ToLongTimeString()}");
}
}
So, with 500 ms times 10 restarts this verifies one event at 5 seconds from the start.
You can combine a state variable and a delay to avoid messing with timers or task cancelation. This is far simpler IMO.
Add this state variable to your class/form:
private DateTime _nextRefresh = DateTime.MaxValue;
And here's how you refresh:
private async void Update()
{
await RefreshInOneSecond();
}
private async Task RefreshInOneSecond()
{
_nextRefresh = DateTime.Now.AddSeconds(1);
await Task.Delay(1000);
if (_nextRefresh <= DateTime.Now)
{
_nextRefresh = DateTime.MaxValue;
Refresh();
}
}
If you call RefreshInOneSecond repeatedly, it pushes out the _nextRefresh timestamp until later, so any refreshes already in flight will do nothing.
Demo on DotNetFiddle
One approach is to create a timer and reset this whenever the user does something. For example using System.Timers.Timer
timer = new Timer(1000);
timer.SynchronizingObject = myControl; // Needs a winforms object for synchronization
timer.Elapsed += OnElapsed;
timer.Start(); // Don't forget to stop the timer whenever you are done
...
private void OnUserUpdate(){
timer.Interval = 1000; // Setting the interval will reset the timer
}
There are multiple timers to chose from, I believe the same pattern is possible with the other timers. DispatchTimer might be most suitable if you use WPF.
Note that both System.Timers.Timer and Task.Delay uses System.Threading.Timer in the background. It is possible to use this directly, just call the .Change method to reset it. But be aware that this raises the event on a taskpool thread, so you need to provide your own synchronization.
I implemented the same scenario in a JavaScript application using Timer. I believe it's the same in the .NET world. Anyway handling this use-case when the user calls a method repeatedly with Task.Delay() will put more pressure on GC & thread pool
var timer = new Timer()
{
Enabled = true,
Interval = TimeSpan.FromSeconds(5).TotalMilliseconds,
};
timer.Elapsed += (sender, eventArgs) =>
{
timer.Stop();
// do stuff
}
void OnKeyUp()
{
timer.Stop();
timer.Start();
}

Windows Service recursive & infinite call

I have a Windows Service which connects to an external device (micro controller) to get data and save it to database. The external device does not support callback feature, that's why the service should ask for the data frequently.
What I did so far: I created a service with a timer which ticks frequently, based on configuration.
Here, I have two problems:
Sometimes the data very big, and before collecting and saving that data, the timer is restarting based on configuration. In this case, I'm losing the data.
If I configure the timer for longer period, I'm losing monitoring which data should be monitored immediately after collect.
I've read other related questions like doing a recursive call in the background service, etc. But I don't have exit condition for recursive call. Application should continue working even after some exception occurs.
Here is my code:
public partial class DataManagerService : ServiceBase
{
public DataManagerService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer = new System.Timers.Timer(1000);
timer.Elapsed += new System.Timers.ElapsedEventHandler(OnElapsedTime);
timer.Enabled = true;
}
private void OnElapsedTime(object source, System.Timers.ElapsedEventArgs e)
{
GetRecords();
}
protected override void OnStop()
{
// clean up
}
}
PS: I'm using .NET Framework 4.6.1 and Visual Studio 2017 Community edition
The System.Timers.Timer.Stop documentation contains a (non-trivial) example of how to accomplish this using two Timer instances. At each interval, a separate control Thread leverages:
a static currentTimer field to select the correct Timer instance
the System.Threading.Interlocked.CompareExchange static method to prevent overlapping Elapsed events.
Because I see a little ambiguity in your requirement, let me call out Microsoft's note about the use case for this approach versus System.Threading.Monitor:
If it were necessary to execute every event, the Monitor class would be a better way to synchronize the events.
From Microsoft docs System.Timers.Timer.Stop examples
The following code example shows one way to prevent the thread that calls the Stop method from continuing until a currently executing Elapsed event ends, and also to prevent two Elapsed events from executing the event handler at the same time (often referred to as reentrancy).
The example executes 100 test runs. Each time the test is run, the timer is started with an interval of 150 milliseconds. The event handler uses the Thread.Sleep method to simulate a task that randomly varies in length from 50 to 200 milliseconds. The test method also starts a control thread that waits for a second and then stops the timer. If an event is being handled when the control thread stops the timer, the control thread must wait until the event is finished before proceeding.
The Interlocked.CompareExchange(Int32, Int32, Int32) method overload is used to avoid reentrancy and to prevent the control thread from continuing until an executing event ends. The event handler uses the CompareExchange(Int32, Int32, Int32) method to set a control variable to 1, but only if the value is currently zero. This is an atomic operation. If the return value is zero, the control variable has been set to 1 and the event handler proceeds. If the return value is non-zero, the event is simply discarded to avoid reentrancy. (If it were necessary to execute every event, the Monitor class would be a better way to synchronize the events.) When the event handler ends, it sets the control variable back to zero. The example records the total number of events that executed, that were discarded because of reentrancy, and that occurred after the Stop method was called.
The control thread uses the CompareExchange(Int32, Int32, Int32) method to set the control variable to -1 (minus one), but only if the value is currently zero. If the atomic operation returns non-zero, an event is currently executing. The control thread waits and tries again. The example records the number of times the control thread had to wait for an event to finish.
using System;
using System.Timers;
using System.Threading;
public class Test
{
// Change these values to control the behavior of the program.
private static int testRuns = 100;
// Times are given in milliseconds:
private static int testRunsFor = 500;
private static int timerIntervalBase = 100;
private static int timerIntervalDelta = 20;
// Timers.
private static System.Timers.Timer Timer1 = new System.Timers.Timer();
private static System.Timers.Timer Timer2 = new System.Timers.Timer();
private static System.Timers.Timer currentTimer = null;
private static Random rand = new Random();
// This is the synchronization point that prevents events
// from running concurrently, and prevents the main thread
// from executing code after the Stop method until any
// event handlers are done executing.
private static int syncPoint = 0;
// Count the number of times the event handler is called,
// is executed, is skipped, or is called after Stop.
private static int numEvents = 0;
private static int numExecuted = 0;
private static int numSkipped = 0;
private static int numLate = 0;
// Count the number of times the thread that calls Stop
// has to wait for an Elapsed event to finish.
private static int numWaits = 0;
[MTAThread]
public static void Main()
{
Timer1.Elapsed += new ElapsedEventHandler(Timer1_ElapsedEventHandler);
Timer2.Elapsed += new ElapsedEventHandler(Timer2_ElapsedEventHandler);
Console.WriteLine();
for(int i = 1; i <= testRuns; i++)
{
TestRun();
Console.Write("\rTest {0}/{1} ", i, testRuns);
}
Console.WriteLine("{0} test runs completed.", testRuns);
Console.WriteLine("{0} events were raised.", numEvents);
Console.WriteLine("{0} events executed.", numExecuted);
Console.WriteLine("{0} events were skipped for concurrency.", numSkipped);
Console.WriteLine("{0} events were skipped because they were late.", numLate);
Console.WriteLine("Control thread waited {0} times for an event to complete.", numWaits);
}
public static void TestRun()
{
// Set syncPoint to zero before starting the test
// run.
syncPoint = 0;
// Test runs alternate between Timer1 and Timer2, to avoid
// race conditions between tests, or with very late events.
if (currentTimer == Timer1)
currentTimer = Timer2;
else
currentTimer = Timer1;
currentTimer.Interval = timerIntervalBase
- timerIntervalDelta + rand.Next(timerIntervalDelta * 2);
currentTimer.Enabled = true;
// Start the control thread that shuts off the timer.
Thread t = new Thread(ControlThreadProc);
t.Start();
// Wait until the control thread is done before proceeding.
// This keeps the test runs from overlapping.
t.Join();
}
private static void ControlThreadProc()
{
// Allow the timer to run for a period of time, and then
// stop it.
Thread.Sleep(testRunsFor);
currentTimer.Stop();
// The 'counted' flag ensures that if this thread has
// to wait for an event to finish, the wait only gets
// counted once.
bool counted = false;
// Ensure that if an event is currently executing,
// no further processing is done on this thread until
// the event handler is finished. This is accomplished
// by using CompareExchange to place -1 in syncPoint,
// but only if syncPoint is currently zero (specified
// by the third parameter of CompareExchange).
// CompareExchange returns the original value that was
// in syncPoint. If it was not zero, then there's an
// event handler running, and it is necessary to try
// again.
while (Interlocked.CompareExchange(ref syncPoint, -1, 0) != 0)
{
// Give up the rest of this thread's current time
// slice. This is a naive algorithm for yielding.
Thread.Sleep(1);
// Tally a wait, but don't count multiple calls to
// Thread.Sleep.
if (!counted)
{
numWaits += 1;
counted = true;
}
}
// Any processing done after this point does not conflict
// with timer events. This is the purpose of the call to
// CompareExchange. If the processing done here would not
// cause a problem when run concurrently with timer events,
// then there is no need for the extra synchronization.
}
// Event-handling methods for the Elapsed events of the two
// timers.
//
private static void Timer1_ElapsedEventHandler(object sender,
ElapsedEventArgs e)
{
HandleElapsed(sender, e);
}
private static void Timer2_ElapsedEventHandler(object sender,
ElapsedEventArgs e)
{
HandleElapsed(sender, e);
}
private static void HandleElapsed(object sender, ElapsedEventArgs e)
{
numEvents += 1;
// This example assumes that overlapping events can be
// discarded. That is, if an Elapsed event is raised before
// the previous event is finished processing, the second
// event is ignored.
//
// CompareExchange is used to take control of syncPoint,
// and to determine whether the attempt was successful.
// CompareExchange attempts to put 1 into syncPoint, but
// only if the current value of syncPoint is zero
// (specified by the third parameter). If another thread
// has set syncPoint to 1, or if the control thread has
// set syncPoint to -1, the current event is skipped.
// (Normally it would not be necessary to use a local
// variable for the return value. A local variable is
// used here to determine the reason the event was
// skipped.)
//
int sync = Interlocked.CompareExchange(ref syncPoint, 1, 0);
if (sync == 0)
{
// No other event was executing.
// The event handler simulates an amount of work
// lasting between 50 and 200 milliseconds, so that
// some events will overlap.
int delay = timerIntervalBase
- timerIntervalDelta / 2 + rand.Next(timerIntervalDelta);
Thread.Sleep(delay);
numExecuted += 1;
// Release control of syncPoint.
syncPoint = 0;
}
else
{
if (sync == 1) { numSkipped += 1; } else { numLate += 1; }
}
}
}
/* On a dual-processor computer, this code example produces
results similar to the following:
Test 100/100 100 test runs completed.
436 events were raised.
352 events executed.
84 events were skipped for concurrency.
0 events were skipped because they were late.
Control thread waited 77 times for an event to complete.
*/

C# WinForms Trying to Update UI with Timer but without slowing the performance down

so currently I've got an application that has 2 processes. One process is pining, while pinging the process is writing down the results into an array.
Another process is for updating the UI every second with a timer. Whats being update is an mschart to be more exact.
That's how I have set up the timer:
readonly System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
myTimer.Interval = 1000;
myTimer.Tick += WriteFunction;
Now this is the method that I'm calling every second for refreshing the UI / actually Graph:
private void WriteFunction(object objectInfo, EventArgs e)
{
foreach (NetPinger.source.AddGraph b in graphList)
{
b.fileRead();
}
}
The method, for updating the chart is inside another class, and looks like this:
public void fileRead()
{
double unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
chart_holder.Series[0].Points.Clear();
for (double i = unixTimestamp; unixTimestamp - graphSizing < i; i--)
{
bool exists;
try
{
exists = Array.Exists(file, element => element.XValue == i);
exists = true;
}
catch
{
exists = false;
}
try
{
if (exists == false)
{
DataPoint point = new DataPoint(i, 0);
chart_holder.Series[0].Points.Add(point);
}
else
{
DataPoint point = Array.Find(file, element => element.XValue == i);
chart_holder.Series[0].Points.Add(point);
}
}
catch(Exception ex)
{
MessageBox.Show(Convert.ToString(ex));
}
}
}
Now what I noticed was that if the graphSizing (number that I'm looping through) is kept low, the performance is kinda fine and everything is sync (multiple graphs from UI are updated at same time etc.) like it should be. But as soon as i rise it let's say to like 50 or even 250 (what the goal should be) the UI and Graph updating are being very very slow. It's only updating like every 3s and the UI is in general very laggy and slow.
Does anyone has any advice how I can maintain good performance or where I messed up that the UI is so slow? For further questions or more details feel free to ask.
Thanks a lot for your time and helping.
Greetings C.User
Your code always runs in the UI thread, since System.Windows.Forms.Timer calls the delegate on the UI thread. Even if that where not the case (and you used System.Timer instead), you delegate everything back to the UI with your Invoke call. You need to make sure you prepare the data on another thread first and do as little as possible in the UI thread itself.

c# looping method in WPF

I am sure this may have been answer somewhere but I have searched all over the web and cannot find an obvious solution?
private void button5_Click(object sender, RoutedEventArgs e)
{
if (stopwatch.IsRunning == false)
{
stopwatch.Start();
while (stopwatch.IsRunning == true)
{
label7.Content = stopwatch.Elapsed.ToString();
Thread.Sleep(1000);
}
}
}
label7 does not update and I am assuming its because the while loop never exits?
but I also tried this with no joy?
private void button5_Click(object sender, RoutedEventArgs e)
{
if (stopwatch.IsRunning == false)
{
stopwatch.Start();
}
label7.Content = stopwatch.Elapsed.ToString();
Thread.Sleep(1000);
button5_Click(sender, e);
}
You don't want to do a Thread.Sleep(1000) in there. That will make it so that the UI won't be able to update itself. Instead, use a timer and when the timer tick event fires, change the text in the label.
So for your example, when you define the stopwatch, define its interval and then add an event handler for the 'Tick' event. When it 'ticks' set the content of your label.
Use a DispatcherTimer so that you don't have to shift to the UI thread, as your timer will work within the UI thread for you.
Since you are creating a timer class, you should use the Timer Elapsed event. Update your UI in there.
MSDN Timer Elapsed Event Description
As has been said, sleeping your process thread will essentially freeze the application. Generally avoid it if you can unless you have a very specific reason to sleep a thread. 1 second is also an eternity for a computer, so your elapsed time increments should be relatively small. A user will notice 1 second, they will have a harder time notice increments of .1 s and less.

Pause execution of a method without locking GUI. C#

I'm working on a card game in C# for a project on my Intro to OOP paper and have got the game working now but am adding "flair" to the GUI.
Currently cards are dealt and appear on the UI instantaneously. I want to have to program pause for a moment after dealing a card before it deals the next.
When a game is started the following code runs to populate the PictureBoxes that represent them (will be a loop eventually):
cardImage1.Image = playDeck.deal().show();
cardImage2.Image = playDeck.deal().show();
cardImage3.Image = playDeck.deal().show();
cardImage4.Image = playDeck.deal().show();
cardImage5.Image = playDeck.deal().show();
...
I have tries using System.Threading.Thread.Sleep(100); between each deal().show() and also inside each of those methods but all it achieves is locking up my GUI until all of the sleeps have processed then display all of the cards at once.
I have also tried using a combination of a timer and while loop but it resulted in the same effect.
What would be the best way of achieving the desired result?
The problem is that any code that you run on the UI will block the UI and freeze the program. When your code is running (even if it's running Thread.Sleep), messages (such as Paint or Click) sent to the UI will not be processed (until control returns to the message loop when you exit your event handler), causing it to freeze.
The best way to do this is to run on a background thread, and then Invoke to the UI thread between sleeps, like this:
//From the UI thread,
ThreadPool.QueueUserWorkItem(delegate {
//This code runs on a backround thread.
//It will not block the UI.
//However, you can't manipulate the UI from here.
//Instead, call Invoke.
Invoke(new Action(delegate { cardImage1.Image = playDeck.deal().show(); }));
Thread.Sleep(100);
Invoke(new Action(delegate { cardImage2.Image = playDeck.deal().show(); }));
Thread.Sleep(100);
Invoke(new Action(delegate { cardImage3.Image = playDeck.deal().show(); }));
Thread.Sleep(100);
//etc...
});
//The UI thread will continue while the delegate runs in the background.
Alternatively, you could make a timer and show each image in the next timer tick. If you use a timer, all you should do at the beginning is start the timer; don't wait for it or you'll introduce the same problem.
Normally I'd simply recommend a function like this to perform a pause while allowing the UI to be interactive.
private void InteractivePause(TimeSpan length)
{
DateTime start = DateTime.Now;
TimeSpan restTime = new TimeSpan(200000); // 20 milliseconds
while(true)
{
System.Windows.Forms.Application.DoEvents();
TimeSpan remainingTime = start.Add(length).Subtract(DateTime.Now);
if (remainingTime > restTime)
{
System.Diagnostics.Debug.WriteLine(string.Format("1: {0}", remainingTime));
// Wait an insignificant amount of time so that the
// CPU usage doesn't hit the roof while we wait.
System.Threading.Thread.Sleep(restTime);
}
else
{
System.Diagnostics.Debug.WriteLine(string.Format("2: {0}", remainingTime));
if (remainingTime.Ticks > 0)
System.Threading.Thread.Sleep(remainingTime);
break;
}
}
}
But there seems to be some complication in using such a solution when it is called from within an event handler such as a button click. I think the system wants the button click event handler to return before it will continue processing other events because if I try to click again while the event handler is still running, the button depresses again even though I'm trying to drag the form and not click on the button.
So here's my alternative. Add a timer to the form and create a dealer class to handle dealing with cards by interacting with that timer. Set the Interval property of the timer to match the interval at which you want cards to be dealt. Here's my sample code.
public partial class Form1 : Form
{
CardDealer dealer;
public Form1()
{
InitializeComponent();
dealer = new CardDealer(timer1);
}
private void button1_Click(object sender, EventArgs e)
{
dealer.QueueCard(img1, cardImage1);
dealer.QueueCard(img2, cardImage2);
dealer.QueueCard(img3, cardImage1);
}
}
class CardDealer
{
// A queue of pairs in which the first value represents
// the slot where the card will go, and the second is
// a reference to the image that will appear there.
Queue<KeyValuePair<Label, Image>> cardsToDeal;
System.Windows.Forms.Timer dealTimer;
public CardDealer(System.Windows.Forms.Timer dealTimer)
{
cardsToDeal = new Queue<KeyValuePair<Label, Image>>();
dealTimer.Tick += new EventHandler(dealTimer_Tick);
this.dealTimer = dealTimer;
}
void dealTimer_Tick(object sender, EventArgs e)
{
KeyValuePair<Label, Image> cardInfo = cardInfo = cardsToDeal.Dequeue();
cardInfo.Key.Image = cardInfo.Value;
if (cardsToDeal.Count <= 0)
dealTimer.Enabled = false;
}
public void QueueCard(Label slot, Image card)
{
cardsToDeal.Enqueue(new KeyValuePair<Label, Image>(slot, card));
dealTimer.Enabled = true;
}
}
The cheap way out would be to loop with calls to Application.DoEvents() but a better alternative would be to set a System.Windows.Forms.Timer which you would stop after the first time it elapses. In either case you'll need some indicator to tell your UI event handlers to ignore input. You could even just use the timer.Enabled property for this purpose if it's simple enough.
I would try puting the code that deals the deck ( and calls Thread.Sleep) in another thread.

Categories

Resources