blah blah blah is here! blah blah » Close

up0down
link

Hi,
I have an application running using serial comms & timers etc. I need a stop now button.
At the moment I am using a standard button which when clicked gets over taken by other events.
Is there a way changing the order which the button is handled (there was in VB6!)

Thanks Glenn

last answered one year ago

2 answers

up1down
link

It sounds like your app is using the main thread to do some heavy work. If that's the case, the Click event will not be handled until the main thread returns from the work and handles it. To prevent this, execute the work in a separate (worker) thread or something like the BackgroundWorker class.

GlennP
329

Hi, Things are a little clogged to say the least. Is there a good tutorial on line somewhere I can look at that gives quick and dirty BackgroundWorker as my previous use of them has given some interesting results. Thanks Glenn

MickW
151

I have exactly the same issue Glenn and was looking for data on this myself. http://www.codeproject.com/KB/threads/csharp.aspx Is good for a beginners guide to threads.

GlennP
329

Thanks- Glenn

up0down
link

The BackgroundWorker is used something like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
private BackgroundWorker worker;

public Form1()
{
InitializeComponent();
worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
worker.WorkerReportsProgress = true;
}

void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
if (e.ProgressPercentage == 100)
label1.Text = "Calculation complete!";
}

void worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i < 101; i++)
{
worker.ReportProgress(i);
Thread.Sleep(50);
}
}

private void button1_Click(object sender, EventArgs e)
{
label1.Text = "Calculating...";
worker.RunWorkerAsync();
}
}
}


Download this to take a closer look.

GlennP
329

As above thanks! Glenn

MickW
151

So if you had a procedure to run inside this - it would go in the "worker_DoWork" method?

foamy
2499

Yes, that's where the 'heavy' code should go. Note that if the code needs to alter the UI, you will need to use some delegates for it to work

Feedback