Add multiple timer with for loop C# - c#

I need 40 timers in my program but I want to create these dynamically.
System.Timers.Timer timermatrix1=new System.Timers.Timer();
timermatrix1.Enabled = true;
timermatrix1.Interval = 10;
timermatrix1.Elapsed += Timermatrix1_Elapsed;
private void Timermatrix1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
.....
}
This code can create one timer but I need 40.So How can I do?

Create an array and initialize them in a loop:
System.Timers.Timer[] timerMatrix = new System.Timers.Timer[40];
for(int i=0; i < 40; i++){
timerMatrix[i] = new System.Timers.Timer() {
Enabled = true,
Interval = 10
};
timerMatrix[i].Elapsed += (sender, e) => {
//TODO: add timer logic
};
}

Related

Timer firing every second and updating GUI (C# Windows Forms)

I have a Windows Forms application where I need to have a timer working for 90 seconds and every second should be shown after it elapses, kind of like a stopwatch 1..2..3 etc, after 90 seconds is up, it should throw an exception that something is wrong.
I have the following code, but the RunEvent never fires.
private void ScanpXRF()
{
bool demo = false;
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
try
{
for (int timerCounter = 0; timerCounter < 90; timerCounter++)
{
timer.Interval = 1000;
timer.Tick += new EventHandler(RunEvent);
timer.Start();
if(timerCounter == 89) {
throw new Exception();
}
}
}
catch (Exception e)
{
timer.Dispose();
MessageBox.Show("There is a problem!");
}
}
private void RunEvent(object sender, System.EventArgs e)
{
//boxStatus.AppendText("RunEvent() called at " + DateTime.Now.ToLongTimeString() + "\n");
MessageBox.Show("timer fired!");
}
Is there anything I am doing wrong here or are there other suggestions for other ways to achieve the same result?
A timer needs to be declared at the form level, or else it may not be disposed of when the form closes:
System.Windows.Forms.Timer timer;
int counter = 0;
Your starting code should just start the timer:
private void ScanpXRF()
{
counter = 0;
timer = new System.Windows.Forms.Timer();
timer.Interval = 1000;
timer.Tick += RunEvent;
timer.Start();
}
The RunEvent is your Tick event being called every second, so your logic needs to go in there:
private void RunEvent(object sender, EventArgs e)
{
counter++;
if (counter >= 90) {
timer.Stop();
// do something...
}
}
made it work
private void ScanpXRF()
{
_pXRFTimerCounter = 0;
pXRFTimer.Enabled = true;
pXRFTimer.Interval = 1000;
pXRFTimer.Elapsed += new ElapsedEventHandler(pXRFTimer_Tick);
pXRFTimer.Start();
}
private static void pXRFTimer_Tick(Object sender, EventArgs e)
{
_pXRFTimerCounter++;
if (_pXRFTimerCounter >= 90)
{
pXRFTimer.Stop();
// do something...
}
else
{
MessageBox.Show(_pXRFTimerCounter.ToString() + " seconds passed");
}
}
I made the timer
System.Timers

Getting a label to insert text slowly

I am trying to insert text to a lable, BUT the text has to be inserted slowly/character by character/letter by letter,
kinda like in old MUD games.
So far I have tried doing this:
private void StoryBox_Click(object sender, EventArgs e)
{
string text = StoryBox.Text;
var index = 0;
var timer = new System.Timers.Timer(2000);
timer.Elapsed += delegate
{
if (index < text.Length)
{
index++;
StoryBox.Text = "This should come out pretty slowly ";
}
else
{
timer.Enabled = false;
timer.Dispose();
}
};
timer.Enabled = true;
}
This is what I have gathered from the site but I don't particularly understand why this isn't working.
As you can see it's under StoryBox_Click.
Is there a way to automate this? So when the program is opened, it counts a couple seconds and THEN starts writing the text out.
Try this:
private async void button1_Click(object sender, EventArgs e)
{
string yourText = "This should come out pretty slowly";
label1.Text = string.Empty;
int i = 0;
for (i = 0; i <= yourText.Length - 1; i++)
{
label1.Text += yourText[i];
await Task.Delay(500);
}
}
You can use the Shown-Event of YourForm when you want to start it after your GUI has been opened.
So reusing your provided code and changing a few things this may work for you:
Add private fields to YourForm class:
private Timer _timer;
private int _index;
private string _storyText;
and initialising it in YourForm constructor
public YourForm()
{
InitializeComponent();
// init private fields;
this._index = 0;
this._storyText = "This should come out pretty slowly";
// Timer Interval is set to 1 second
this._timer = new Timer { Interval = 1000 };
// Adding EventHandler to Shown Event
this.Shown += this.YourForm_Shown;
this._timer.Tick += delegate
{
if (this._index < this._storyText.Length)
{
StoryBox.Text += this._storyText[this._index];
this._index++;
}
else
{
this._timer.Stop();
}
};
}
and the Shown event for YourForm:
private void YourForm_Shown(object sender, EventArgs e)
{
this._timer.Start();
}

Progress bar is jumping

When I start program, I need to load some projects and init them. So I make that all in Thread and create a progress bar (next PB). When loading is started everythink is OK, but in one moment PB is stop and jump to end when init will end.
Here Thread which add to progress bar every init bLock.
public void initMapBlocks(int n, int m)
{
this.Dispatcher.Invoke(delegate ()
{
Loader.Visibility = Visibility.Visible;
mainWindow.Visibility = Visibility.Hidden;
});
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
this.Dispatcher.Invoke(delegate ()
{
MapPart mp = new MapPart();
mainCanvas.Children.Add(mp);
Loader.addPoint(1);
});
}
}
this.Dispatcher.Invoke(delegate ()
{
Loader.Visibility = Visibility.Hidden;
mainWindow.Visibility = Visibility.Visible;
});
}
Did it`s possible to get full animation?
-------- Update --------
Here code where i add to progress bar value.
public void addPoint(int x)
{
itemCountAlready += x;
loaderBar.Value += x;
}
----- Update 2 -------
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Thread thread = new Thread(new ThreadStart(() => initMapBlocks(100, 100)));
thread.Start();
}
Your initMapBlocks method produces (MapPart) and consumes (adds loader's value and mainCanvas children) at the same time. You can separate by using System.Collections.Generic.Queue
You can define your queue like this
private Queue<MapPart> myQueue = new Queue<MapPart>();
Instead of these guys
mainCanvas.Children.Add(mp);
Loader.addPoint(1);
You can write simply this for produce
myQueue.Enqueue(mp);
And you can define a DispatcherTimer in your constructor for consume
DispatcherTimer myTimer = new DispatcherTimer {
Interval = TimeSpan.FromMilliseconds(1)
};
myTimer.Tick += Consume;
myTimer.Start();
Your Consume method
private void Consume(object sender, EventArgs args) {
if (myQueue.Count > 0) {
//you don't need `this.Dispatcher.Invoke(delegate...` too
loaderBar.Value += myQueue.Dequeue();
mainCanvas.Children.Add(mp);
}
}

how to create multiple countdown timers in c# windows application form?

I had created multiple timers using for loop and the timers are diplayed in the corresponding labels.If i click the button "n" times then "n" times ll be created.This code shows error in time countdown during runtime. Each timer is getting decremented by different intervals.How to resolve this problem?
public Dictionary<Timer, Label> dict = new Dictionary<Timer, Label>();
int n = 1;
int timesec = 10;
private void CreateTimers()
{
for (int i = 1; i <= n; i++)
{
Timer timer = new Timer();
timer = new System.Windows.Forms.Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = (1000);//1 sec
Label label = new Label();
label.Name = "label" + i;
label.Location = new Point(0, 100 + i * 30);
label.TabIndex = i;
label.Visible = true;
this.Controls.Add(label);
dict[timer] = label;
timer.Enabled = true;
timer.Start();
}
private void button2_Click(object sender, EventArgs e)
{
//function call
CreateTimers();
n++;
}
private void timer_Tick(object sender, EventArgs e)
{
//timer countdown
Timer t = (Timer)sender;
timesec--;
if (timesec == 0)
t.Stop();
dict[t].Text = timesec.ToString();
}
A couple of issues. First and foremost, you have to eliminate that loop, since that creates more timers than you probably realize. Also, since you want each timer to be independent, you can't change the timesec value.
Try using the value of the label to show the count down, something like this:
private void CreateTimer() {
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Tick += timer_Tick;
timer.Interval = (1000);//1 sec
Label label = new Label();
label.Name = "label" + n.ToString();
label.Text = timesec.ToString();
label.Location = new Point(0, 100 + n * 30);
label.Visible = true;
this.Controls.Add(label);
dict.Add(timer, label);
timer.Enabled = true;
timer.Start();
n++;
}
private void timer_Tick(object sender, EventArgs e) {
System.Windows.Forms.Timer t = (System.Windows.Forms.Timer)sender;
Label l = dict[t];
int labelTime = 0;
if (Int32.TryParse(l.Text, out labelTime)) {
labelTime -= 1;
}
l.Text = labelTime.ToString();
if (labelTime == 0) {
t.Stop();
}
}

Periodic printing of shapes

I am making an application using WPF and C#. What I'm trying to do is to print a lots of shapes on a canvas with some time in between when I push a button. At the moment when I push the button, everything just pops up at once. I have tried to sleep the thread for some time between every "print" but that doesn't help, it just take longer time before everything splash up at once. What I want to achive is that the shapes pop up one at a time with lets say 0.5 seconds in between. The code is the following:
private void Create_Click(object sender, RoutedEventArgs e)
{
Random random = new Random();
for (int i = 0; i < 50; i++)
{
Thread.Sleep(500);
Path f = FlowerFactory.createFlower(FlowerBP, true);
Canvas.SetLeft(f, random.Next(0, 1650));
Canvas.SetTop(f, random.Next(0,1000));
DrawBoard.Children.Add(f);
}}
You need to, first, run the loop in a background thread so that it doesn't block the UI from updating; and second, send the UI-rendering tasks back to the UI thread. For the first, you can use Task.Factory.StartNew, and for the second, use Dispatcher.Invoke:
Random random = new Random();
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 50; i++)
{
Thread.Sleep(500);
Dispatcher.Invoke(DispatcherPriority.Render, new Action(() =>
{
Path f = FlowerFactory.createFlower(FlowerBP, true);
Canvas.SetLeft(f, random.Next(0, 1650));
Canvas.SetTop(f, random.Next(0,1000));
DrawBoard.Children.Add(f);
}));
}
});
It was bad decision to sleep your main thread that responsible for GUI.
Try to use DispatchTimer. For example:
DispatcherTimer m_dispatcherTimer = new DispatcherTimer();
int m_count = 50;
private void Init()
{
m_dispatcherTimer.Tick += new EventHandler(OnTick);
m_dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
}
private void Create_Click(object sender, RoutedEventArgs e)
{
m_count = 50;
m_dispatcherTimer.Start();
}
private void OnTick(object sender, EventArgs e)
{
// Draw your shapes here
if(0>=--m_count)
{
m_dispatcherTimer.Stop();
}
}
using System.Reactive.Concurrency;
using System.Reactive.Linq;
...
var subscription = Observable.Interval(TimeSpan.FromSeconds(0.5)).Take(50).Subscribe(x=>CreateRandomFlower);

Categories

Resources