I have a problem with following, very simplified case being part of my project. Consider we have GUI like below:
I have two background workers:
plot_bgworker - in this example, it increments plot counter,
data_bgworker - in this example, it increments data counter.
I also have label_timer, which updates incremented values diplayed on my form.
To manage both background workers and timer, I wrote two functions:
private: void turnOnAcquisition() {
if (!counting_paused)
return;
if (!plot_bgworker->IsBusy)
plot_bgworker->RunWorkerAsync();
if (!data_bgworker->IsBusy)
data_bgworker->RunWorkerAsync();
label_timer->Enabled = true;
counting_paused = false;
}
private: void turnOffAcquisition() {
if (counting_paused)
return;
if (plot_bgworker->IsBusy)
plot_bgworker->CancelAsync();
if (data_bgworker->IsBusy)
data_bgworker->CancelAsync();
label_timer->Enabled = false;
counting_paused = true;
}
Then, here is what happens when I click each of my buttons:
// Pauses counting on click
private: System::Void stop_btn_Click(System::Object^ sender, System::EventArgs^ e) {
turnOffAcquisition();
}
// Starts counting on click
private: System::Void start_btn_Click(System::Object^ sender, System::EventArgs^ e) {
turnOnAcquisition();
}
// Should restart counting on click, beginning from 0 (no matter what state counting is in right now)
private: System::Void restart_btn_Click(System::Object^ sender, System::EventArgs^ e) {
plot_counter = 0;
data_counter = 0;
turnOffAcquisition();
turnOnAcquisition();
}
Finally, here are my background workers (turned off / on by CancelAsync() / RunWorkerAsync() ) and timer:
// Calculating data counter
private: System::Void data_bgworker_DoWork(System::Object^ sender, System::ComponentModel::DoWorkEventArgs^ e) {
for (;;) {
data_counter++;
Sleep(50);
if (data_bgworker->CancellationPending) {
e->Cancel = true;
return;
}
}
}
// Calculating plot counter
private: System::Void plot_bgworker_DoWork(System::Object^ sender, System::ComponentModel::DoWorkEventArgs^ e) {
for (;;) {
plot_counter++;
Sleep(120);
if (plot_bgworker->CancellationPending) {
e->Cancel = true;
return;
}
}
}
// Display counters
private: System::Void label_timer_Tick(System::Object^ sender, System::EventArgs^ e) {
plot_counter_label->Text = numToMStr(plot_counter);
data_counter_label->Text = numToMStr(data_counter);
}
Start button and stop button work both as expected, but now I have a problem with restart button. When I click it in the middle of counting, it seems to reset values and stop background workers, but never start them again (as I would expect after calling turnOnAcquisition). However, when I click it when counting is off, I am able to turn on counting as expected.
My first shot was that cancellation flag is not yet set to another value when I tried to check if my workers were busy, but using Sleep() between calls didn't work. Another guess is that it is due to race condition failure, so I tried using MemoryBarrier(), but I don't know the libraries and I'm not sure if it would work. Also, I tried to use Interlocked class, but couldn't use it properly for void functions.
1. Is this way of thinking correct?
2. If yes, why simple Sleep() doesn't do the trick?
3. How would I use any of mentioned methods in this case and which one would be the best match?
Ok, I found the solution by myself. The problem here was about the race condition - one event tried to stop counting (which meant raising another event) and then starting it again (which was problematic, as my function (I guess) was already cluttered with the first one and probably the second event wasn't even added to the event detected queue). If I am wrong with the explanation, I would appreciate some criticism down there ;)
Here are two modified functions, which solved thread management correctly. The key was to let the other events do their work until I get desired state.
When I want to turn off counting, I let the applications do the events from the queue until both threads will not be busy (the 'while' loop):
private: void turnOffAcquisition() {
if (counting_paused)
return;
if (plot_bgworker->IsBusy)
plot_bgworker->CancelAsync();
if (data_bgworker->IsBusy)
data_bgworker->CancelAsync();
while((plot_bgworker->IsBusy) || (data_bgworker->IsBusy)) // Continue to process events until both workers stop working
Application::DoEvents(); // Then, you can process another thread requests! :)
label_timer->Enabled = false;
counting_paused = true;
}
Similarily, when I want to restart counting, I let the application do the events until I check that both threads are busy (again, the 'while' loop):
private: void turnOnAcquisition() {
if (!counting_paused)
return;
if (!plot_bgworker->IsBusy)
plot_bgworker->RunWorkerAsync();
if (!data_bgworker->IsBusy)
data_bgworker->RunWorkerAsync();
while((!plot_bgworker->IsBusy) || (!data_bgworker->IsBusy)) // Continue to process events until both workers start working
Application::DoEvents(); // Then, you can process another thread requests! :)
label_timer->Enabled = true;
counting_paused = false;
}
Related
I just began learning WinForms and am currently baffled on how to get the senders' (mouses') position (coordinates). I tried searching but to no avail.
This is my, somewhat, of a try but, sadly, it ended up with an error:
private: System::Void pictureBox1_MouseHover(System::Object^ sender, System::EventArgs^ e) {
this->pictureBox1->Location = System::Drawing::Point(sender::Position.X - 5, sender::Position.Y - 5);
MessageBox::Show("Foo", "Bar", MessageBoxButtons::OK, MessageBoxIcon::Stop);
}
So my question here is quite clear, I think: how can I get the senders' position (in this case, the mouses'). Explanations would also be of help. Thank you.
Since I didn't find a valid answer I took the longer route.
Firstly, I declared a boolean in the namespace with the value of false (it will change to true when the mouse will touch the picture). Then I create two new methods: one to get the X and Y of the mouse and execute code if the mouse is touching the picture and the second one to determine whether the mouse is touching the picture or not.
private: System::Void picture_MouseMove(Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
int VMouseX = e->X,
VMouseY = e->Y;
if (VMouseEntered) {
VMouseEntered = false;
this->picture->Location = System::Drawing::Point(VMouseX + 17, VMouseY + 17);
}
}
private: System::Void picture_MouseEnter(System::Object^ sender, System::EventArgs^ e) {
VMouseEntered = true;
}
Then, I create two new EventHandlers for the picture. The first EventHandler is to listen for mouse movement, the second one is to check whether the mouse is touching the picture.
this->picture->MouseMove += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::picture_MouseMove); // Checks for mouse movement.
this->picture->MouseEnter += gcnew System::EventHandler(this, &Form1::picture_MouseEnter); // Checks whether the mouse is touching the picture.
Done. I hope that this will help someone.
I am currently building a windows form application and I have got the next problem,
I can't declare a variable global because the syntax im using won't allow me to do that, also, i need to declare the variable in the method it self and at last, it must loop so its able to count. This is what I have got so far:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
int i;
m_bIsTimerOn = true;
while (m_bIsTimerOn)
{
i++;
label1->Text = (i.ToString());
}
}
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
m_bIsTimerOn = false;
timer1->Enabled = false;
}
m_bIsTimerOn is a globally boolean. As you might see here my problem is if i press button1 the program is just stuck in the while loop. I would like to know that the moment you press button2 the while loop stops I also would like to know if this is even possible. If you could response in c++ that would also be fine.
Thank you in advance.
I suppose you want to increment i while timer is on. If you need to update i for each timer tick then it's pretty easy, remove that loop (and that variable BTW) and simply do update inside timer Tick event:
private:
int _i;
void button1_Click(Object^ sender, EventArgs^ e) {
_i = 0;
timer1->Enabled = true;
}
void _timer1_Tick(Object^ sender, EventArgs^ e) {
label1->Text = (i++).ToString();
}
void button2_Click(Object^ sender, EventArgs^ e) {
timer1->Enabled = false;
}
If i must be updated independently from timer ticks then you have to move it to a BackgroundWorker or simply in event handler for Application::Idle:
void OnIdle(Object^ sender, EventArgs^ e) {
label1->Text = (_i++).ToString();
}
void button1_Click(Object^ sender, EventArgs^ e) {
_i = 0;
Application::Idle += gcnew EventHandler(this, Form1::OnIdle);
timer1->Enabled = true;
}
void button2_Click(Object^ sender, EventArgs^ e) {
Application::Idle -= gcnew EventHandler(this, Form1::OnIdle);
timer1->Enabled = false;
}
As final note: you may even keep your loop as is and put a call to Application::DoEvents() just after your label1->Text = (i.ToString()); but this will probably consumes a lot of CPU, slow down your application and open your code to reentrancy, I'd really avoid something like that...
Your program is in endless loop because the while loop prevents the messages from getting processed and hence your button2_Click does not get invoked. To make you application capable of processing the messages that occurs, add Application.DoEvents() in your loop as:
while (m_bIsTimerOn)
{
i++;
label1->Text = (i.ToString());
Application.DoEvents(); // causes the application to handle pending events
}
So now, if you press the second button, m_bIsTimerOn will become false and your loop will terminate.
I got a little problem with button events. I programmed one button to decrease specific value by 1 (click), and I want to decrease it over time while holding button pressed. I'm using Silverlight, not XNA.
myTimer.Change(0, 100);
private void OnMyTimerDone(object state)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (rightButton.IsPressed)
{
rightButton_Click(null, null);
}
});
}
this code is correctly working at the beginning, but then I am unable to single tap as it is always calling hold event.
Try to use the RepeatButton silverlight control instead of using a normal Button
Here is an Example of how to use it:
XAML Code:
<RepeatButton x:Name="rbtnDecrease" Content="Decrease" Delay="200" Interval="100" Click="rbtnDecrease_Click" />
Delay: The amount of time, in milliseconds, the RepeatButton waits while it is pressed before it starts repeating.
Interval: The amount of time, in milliseconds, between repeats once repeating starts.
C# Code:
private int tempCount = 100; // A temp Variable used as an Example
private void rbtnDecrease_Click(object sender, RoutedEventArgs e){
// Add your Button Click/Repeat Code Here...
// Example of Decreasing the value of a Variable
tempCount--;
}
Two suggestions, the first being to stop the timer (using a DispatcherTimer) if isPressed is false
void Button_MouseLeftButtonDown(object sender, EventArgs e)
{
myTimer.Start();
}
void OnTimerTick(object s, EventArgs args)
{
if(rightButton.IsPressed == false)
{
myTimer.Stop();
}
else
{
// decrease value
}
}
the second being to stop the timer on the MouseLeftButtonUp event
I'm web developer and I'm trying to step into multithreading programming.
On one form I'm trying to run a method computing values in a second thread using asynchronous delegates.
I also want a progress bar showing actual progress in UI thread been notified.
delegate void ShowProgressDelegate(int total, int value);
delegate void ComputeDelegate(int value);
//Some method simulating sophisticated computing process
private void Compute(int value)
{
ShowProgress(value, 0);
for (int i = 0; i <= value; i++)
{
ShowProgress(value, i);
}
}
//Method returning values into UI thread
private void ShowProgress(int total, int value)
{
if (!this.InvokeRequired)
{
ComputeButton.Text = value.ToString();
ProgressBar.Maximum = total;
ProgressBar.Value = value;
}
else
{
ShowProgressDelegate showDel = new ShowProgressDelegate(ShowProgress);
this.BeginInvoke(showDel, new object[] { total, value });
}
}
//firing all process
private void ComputeButton_Click(object sender, EventArgs e)
{
ComputeButton.Text = "0";
ComputeDelegate compDel = new ComputeDelegate(Compute);
compDel.BeginInvoke(100000, null, null);
}
When I run this, everything is computing without any problem except it is still running in UI thread (I suppose so, because it freezes when I click some button on the form).
Why? I also attach buildable sample project (VS2010) with same code: http://osmera.com/windowsformsapplication1.zip
Thanks for helping neewbie.
In the code you've shown, you're doing nothing other than updating the progress bar - so there are thousands of UI messages to marshal, but nothing significant happening in the non-UI thread.
If you start simulating real work in Compute, you'll see it behave more reasonably, I suspect. You need to make sure you don't swamp the UI thread with progress updates like you are doing now.
I've been searching and found that a good way to perform background work and update the GUI is using background workers. However, doing this (stupid) little task (counting from 1 to 10000) it doesn't update the label content but prints to the debug! (This is just a spike solution for another project of course...)
Here's the code:
public partial class MainWindow : Window
{
BackgroundWorker bw = new BackgroundWorker();
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.WorkerReportsProgress = true;
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("DONE");
}
void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Content = "going here: "+e.ProgressPercentage;
Debug.WriteLine(e.ProgressPercentage);
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i=0; i < 10000; i++)
{
bw.ReportProgress((i*100)/10000);
}
}
}
The ProgressChanged event is raised on the UI thread, not the worker thread. In your code, the worker thread is doing almost nothing (just loop from 0 to 10000 and call ReportProgress), most of the work is done on the UI thread. Basically, you're sending too many progress notifications. Because of this, the UI thread is almost always busy and has no time to render the new content of the label.
Rendering in WPF is not performed immediately when you change a property of a control, it is done on a separate dispatcher frame, which is processed when the dispatcher has nothing more urgent to do, based on the priority of the task. The priority used for rendering has a value of 7 (DispatcherPriority.Render); the ProgressChanged event is marshalled to the UI thread with a priority of 9 (DispatcherPriority.Normal), as specified on MSDN. So the ProgressChanged notifications always have a higher priority than rendering, and since they keep coming, the dispatcher never has time to process the rendering tasks.
If you just decrease the frequency of the notifications, your app should work fine (currently you're sending 100 notifications for each percentage value, which is useless):
void bw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 10000; i++)
{
if (i % 100 == 0)
bw.ReportProgress(i / 100);
}
}
this.Dispatcher.BeginInvoke( (Action) delegate(){
label1.Content = "going here: "+e.ProgressPercentage;
});
Try to change the label using womething like this:
string Text = "going here: " + e.ProgressPercentage;
this.Invoke((MethodInvoker)delegate {
label1.Content = newText;
});
Note that i'm not sure it will work. I can not test it now. If it does not work, let me know and I will delete the answer.
If you need the a canonical way to do exactly what you want, look at the Hath answer in this post: How do I update the GUI from another thread?