How do I make a repeating button with a thread in c#? - 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.

Related

Controls synchronization between several threads in Windows Forms

I have some controls on the form of the Windows Forms application and I need to update its' texts at run-time from several threads.
Is it safe to just call BeginInvoke method like this:
BeginInvoke((MethodInvoker)delegate()
{
this.label.Text = "Some text";
});
from several threads at the same time? Should I do any additional synchronization in this case? Will it be processed by the same thread one by one and is this order guaranteed?
Thanks in advance.
Calling BeginInvoke puts the delegate on to the message queue to be processed by the UI thread, it will process the queue handling the messages one by one. So no, you do not need to do any additional synchronization (as long as the delegate is not accessing any resources that can't be accessed from the UI thread).
As for order, it is not guaranteed they will be processed in order but in practice most of the time the delegates will be processed in the order they where put in to the queue.
To address the question in the comments, instead of using multiple BeginInvoke calls you should be able to get away with just one.
You never really explained what your animation was so I am going to assume it is going to be that this.label will swap between ., .. and ... then you store the result text in this.label when you are done.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
animationTimer = new System.Windows.Forms.Timer();
animationTimer.Interval = 500;
animationTimer.Tick += animationTimer_Tick;
}
private System.Windows.Forms.Timer animationTimer;
private int dots = 0;
void animationTimer_Tick(object sender, EventArgs e)
{
//Make 1, 2, or 3 dots show up. This runs on the UI thread so we don't need to invoke.
this.label.Text = new String('.', dots + 1);
//Add one then reset to 0 if we reach 3.
dots += 1;
dots = dots % 3;
}
private void button1_Click(object sender, EventArgs e)
{
animationTimer.Start();
Task.Run(() => DoSomeSlowCalcuation());
}
private void DoSomeSlowCalcuation()
{
Thread.Sleep(5000);
this.BeginInvoke((MethodInvoker)delegate()
{
//We stop the timer before we set the text so the timer will not overwrite it.
animationTimer.Stop();
this.label.Text = "Some text";
});
}
}
This code is just a example to get my point across, if I where doing this I would use async/await for the button click and not use BeginInvoke at all.
private async void button1_Click(object sender, EventArgs e)
{
animationTimer.Start();
var result = await Task.Run(() => DoSomeSlowCalcuation());
animationTimer.Stop();
this.label.Text = result;
}
private string DoSomeSlowCalcuation()
{
Thread.Sleep(5000);
return "Some text";
}

C# Thread ListView

I'm a fairly new to .net and I'm still struggling to understand a lot things, and right now I'm trying to accomplish something relatively simple but I've failed every single time, I would like to add a Thread to my program, this Thread would be responsible to perform the Upload operations to a web server and keep my program responsive providing the feedback of the operations to my users by updating a ListView, where the users would see all the status of the file uploads.
I don't know how to put this Thread inside the program to make it responsive, I couldn't find any examples so far and I'm trying to find a little sample to show me the use of Thread and WinForms in action.
What you'll want to use is a BackgroundWorker. It's specifically designed for exactly this purpose.
private void button1_Click(object sender, EventArgs e)
{
BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += (_, args) => LongRunningTask(bgw);
bgw.WorkerReportsProgress = true;
bgw.ProgressChanged += (_, args) =>
{
textbox1.Text = args.ProgressPercentage.ToString();
};
bgw.RunWorkerCompleted += bgw_RunWorkerCompleted;
bgw.RunWorkerAsync();
}
private void LongRunningTask(BackgroundWorker bgw)
{
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1000);//placeholder for real work
bgw.ReportProgress(i);
}
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//do stuff when completed.
}
A key point to note is that the DoWork event runs in a background thread, but the other events all run in the UI thread. The BackgroundWorkder class takes care of ensuring that all on its own.

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.

BackgroundWorker thread and Timer logic

I've been trying to get the logic right for my timer and backgroundworker thread. Granted I don't fully understand the whole system despite all my reading. the following are excerpts of code concerned:
My polling button :
private void pollStart_Click(object sender, EventArgs e)
{
tst_bgw = new BackgroundWorker();
//mandatory. Otherwise will throw an exception when calling ReportProgress method
tst_bgw.WorkerReportsProgress = true;
//mandatory. Otherwise we would get an InvalidOperationException when trying to cancel the operation
tst_bgw.WorkerSupportsCancellation = true;
tst_bgw.DoWork += tst_bgw_DoWork;
tst_bgw.ProgressChanged += tst_bgw_ProgressChanged;
tst_bgw.RunWorkerCompleted += tst_bgw_RunWorkerCompleted;
tst_bgw.RunWorkerAsync();
}
which I think is right so far
my Background worker thread:
private void tst_bgw_DoWork(object source, DoWorkEventArgs e)
{
m_timer = new System.Timers.Timer();
m_timer.Interval = 1000;
m_timer.Enabled = true;
m_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
if (tst_bgw.CancellationPending)
{
e.Cancel = true;
return;
}
}
and the elapsed tier event code:
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
if (powerVal > 3250)
{
m_timer.Stop();
tst_bgw.CancelAsync();
}
else
{
string pow;
int progressVal = 100 - ((3250 - powerVal) / timerVal);
uiDelegateTest tstDel = new uiDelegateTest(recvMessage);// the recvMessage function takes a textbox as an argument and directs output from socket to it.
pow = construct_command("power", powerVal);
sData = Encoding.ASCII.GetBytes(pow);
if (active_connection)
try
{
m_sock.Send(sData);
Array.Clear(sData, 0, sData.Length);
tstDel(ref unit_Output);// Read somewhere that you can only modify UI elements in this method via delegate so I think this is OK.
m_sock.Send(time_out_command);
tstDel(ref unit_Output);
tst_bgw.ReportProgress(progressVal);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
tst_bgw.ReportProgress(powerVal, progressVal);
powerVal = powerVal + pwrIncVal;
}
I'd just like to know a few other things; am I using the right timer (not that I think it should matter greatly but it was suggested that this might be the best timer for what I want to do) and canI really modify UI elements in the DoWork method only through delegates and if yes are there sepcial considerations to doing so.
Sorry about the long posting and thank you for your time.
There is lots wrong with this code.
1) You aren't disposing of your background worker. BackgroundWorkers must be disposed of after use. They are designed to be used as winforms components and would normally be added to a window via the designer. This will ensure it is created with the form and disposed of when the form is.
2) All you are doing in your dowork method is creating a new timer and running it. There is no point of doing this in a background worker because it will happen so quickly anyway.
3) You will recreate the timer every time you run the background worker again. But you aren't ever stopping or disposing of the old timer, you are just overwriting the member.
I recommend you get rid of the BackgroundWorker completely and just use a timer. Create the timer in the forms constructor and make sure you dispose of it in the forms dispose method. (Or use the designer to add it to the form). In the pollstart_click method just start the timer. (If you have a poll stop method, you can stop the timer in that)
You don't need both a BackgroundWorker and a Timer to accomplish your goal. From what you have posted it looks like you want to have the user click a button which starts a polling process that quits at a certian point.
Your polling model really suggests a timer would work just fine.
If you use a Timer I would Initialize the timer after the InitializeComponent() call with something like
private void InitializeTimer()
{
this.timer = new Timer();
int seconds = 1;
this.timer.Interval = 1000 * seconds; // 1000 * n where n == seconds
this.timer.Tick += new EventHandler(timer_Tick);
// don't start timer until user clicks Start
}
The button_click will simply
private void button_Click(object sender, EventArgs e)
{
this.timer.Start();
}
Then on the timer_Tick you will need to do your polling and you should be able to update your UI from there if the timer is on the UI thread like this
void timer_Tick(object sender, EventArgs e)
{
if( determineIfTimerShouldStop() )
{
this.timer.Stop();
}
else
{
// write a method to just get the power value from your socket
int powerValue = getPowerValue();
// set progressbar, label, etc with value from method above
}
}
However if the timer thread is not on the same thread as the UI you well get an exception while trying to update the UI. In that case you can use the Invoke that DataDink mentions and do something like this
void timer_Tick(object sender, EventArgs e)
{
if( determineIfTimerShouldStop() )
{
this.timer.Stop();
}
else
{
// write a method to just get the power value from your socket
int powerValue = getPowerValue();
// set a label with Invoke
mylabel.Invoke(
new MethodInvoker( delegate { mylabel.Text = "some string"; } )
);
}
}
Given the code you posted you really didn't need to do both a BackgroundWorker and a Timer, but I have had instances where I have used a BackgroundWorker to do work when a timer is called so that I could have a timer update UI periodically and have a manual button to Refresh the UI. But I wasn't updating my UI quite the way you are.
If you still have the need to do both, here is, roughly, how you can flow your app...
Create an
InitailizeBackgroundWorker() method
along with the InitializeTimer so you have
it already initalized before the
Timer fires.
Then set the Timer.Tick
to call the
BackgroundWorker.RunWorkerAsync()
Then you can do all the UI updates from within the RunWorkerAsync by
using the
BackgroundWorker.ReportProgress().

Categories