Communicating with another thread - c#

This is how I create a thread that does domething reps times:
protected virtual void RedButtonClicked(object sender, System.EventArgs e)
{
Nuker n = new Nuker(target, reps);
bombThread = new Thread(new ThreadStart(n.nuke));
bombThread.Start();
}
The thread class:
public class Nuker
{
private string target;
private int reps;
//...
public void nuke()
{
for(int i=0; i<reps; ++i)
{
ICBM.nuke(target);
Thread.Sleep(5500);
}
System.Console.WriteLine("Done.");
}
}
(I create a new class to store some variables since I can't pass these in ThreadStart().)
Now I would like to have a simple visualisation of the process, let's say printing the current repetition in a text field on a form. How would I use the i from the loop to do that?

In the simplest form you proved a callback in the Nuker class
public Nuker(string target, int reps, Action reportCallback){..}
In the loop you just call reportCallback(i);
Nuker n = new Nuker(target, reps, ReportMethod);
with
private void ReportMethod(int currentIdx)
{
if (InvokeRequired) // Invoke if UI update
...
}
But, probably you want to use the BackgroundWorker that has build in methods for reporting progress on the UI thread. Just check the examples on MSDN.

you can do it with a backgroundworker, it´s one of the easiest threads :-)
below i have post you a sample that i have createt to teach some friends the use of the backgroundworker ;-)
private BackgroundWorker bw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
public void buttonStart_Click(object sender, EventArgs e)
{
if (bw.IsBusy != true)
bw.RunWorkerAsync(12); //Start
}
public int Pils(int i)
{
Thread.Sleep(2000);
bw.ReportProgress(70, "In the middle of the work..");
Thread.Sleep(2000);
bw.ReportProgress(90, "Returning the result..");
Thread.Sleep(2000);
return (2 * i);
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
bw.ReportProgress(20, "Waiting for cancel..");
Thread.Sleep(2000);
if ((bw.CancellationPending == true))
e.Cancel = true;
else
{
bw.ReportProgress(50, "Starting process..");
e.Result = Pils((int)e.Argument);
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
bw.ReportProgress(100, "Work done..");
if ((e.Cancelled == true))
textBox1.Text = "Canceled!";
else if (e.Error != null)
textBox1.Text = ("Error: " + e.Error.Message);
else textBox1.Text = e.Result.ToString();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
if (bw.WorkerSupportsCancellation == true)
bw.CancelAsync();
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
listBox1.Items.Add((e.ProgressPercentage.ToString() + "%") + " - " + e.UserState as String);
}
url to the blogpost: link

Related

How to correctly implement BackgroundWorker to inform user that the task is progressing

The Problem
I have used the project from https://github.com/zaagan/BioMetrix and want to use BackgroundWorker to display a progression during long tasks (Ex: Get Log Data takes about 30 seconds)
What I've done so far
1- Added backgroundWorker1 from Toolbox
2- After InitializeComponent(), I've Added :
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
3- Added those functions:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 10; i++)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
System.Threading.Thread.Sleep(500);
worker.ReportProgress(i * 10);
}
}
}
private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
this.Text = (e.ProgressPercentage.ToString() + "%");
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
this.Text = "Canceled!";
}
else if (e.Error != null)
{
this.Text = "Error: " + e.Error.Message;
}
else
{
this.Text = "Done!";
}
}
I was expecting to view the progression percentage on the main Caption title text while retrieving log data from the device.
You need to assign the event handler to the event
worker.DoWork += backgroundWorker_ProgressChanged;
If you have created a Windows Form you need to looking in events page of the Background Worker properties and find the DoWork event, then assign it a function to run.

While Loop Locks UI Thread

I have a button in my WinForms application with the following Click event:
private void Button_Click(object sender, EventArgs e)
{
treasureFound = false;
refreshNumber = 0;
Label_StartDateTime.Text = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss");
while (!treasureFound)
{
Label_StatusData.Text = "Refreshed " + refreshNumber + " times.";
refreshNumber++;
using (WebClient client = new WebClient())
{
string htmlCode = client.DownloadString(webUrl);
if (htmlCode.Contains("Treasure"))
{
treasureFound = true;
Label_StatusData.Text = "Found.";
// etc etc
}
}
}
}
When the button is clicked, the UI thread locks up (not responding, labels don't update) until the while loop ends.
What can I do to keep the UI responsive? There should only be one WebClient instance at any one time.
you should execute the time-consuming tasks in a separate thread, so it will not block the main thread (aka your UI thread). One way is to use the BackgroundWorker.
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.WorkerReportsProgress = true;
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
Taken from: How to use a BackgroundWorker?

how to return from the background worker to web UI in asp.net

background worker in asp.net does not write the content to the web UI when background worker completed. please tell me the reasons why. and how to recover.???
static BackgroundWorker bwProcess;
[WebMethod()]
public static int GetProgress()
{
return Percentage;
}
background worker starts when click event happen
protected void btnClick_Click(object sender, EventArgs e)
{
bwProcess = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
bwProcess.DoWork += new DoWorkEventHandler(bwProcess_DoWork);
bwProcess.ProgressChanged += new ProgressChangedEventHandler(bwProcess_ProgressChanged);
bwProcess.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwProcess_RunWorkerCompleted);
bwProcess.RunWorkerAsync("AsyncWorker");
}
do work event for the backgroundworker
void bwProcess_DoWork(object sender, DoWorkEventArgs e)
{
bwProcess.ReportProgress(1);
for (int i = 0; i <= 100; i++)
{
if (bwProcess.CancellationPending)
{
e.Cancel = true;
return;
}
bwProcess.ReportProgress(i);
Thread.Sleep(20);
}
e.Result = "100 %";
}
this part is not working. it run nut there is no response
void bwProcess_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Response.WriteFile("D:\\Samples.xlsx");
}
You've passed something to e.Result in DoWork, but you don't anything with it in RunWorkerCompleted.
void bwProcess_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
var text = e.Result as string;
Response.Write(text);
Response.WriteFile("D:\\Samples.xlsx");
}

Fixing thread safe calls from backgroundWorker

using System;
using System.ComponentModel;
using System.Net;
using System.Windows.Forms;
using Ionic.Zip;
namespace downloader
{
public partial class GUI : Form
{
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
public GUI()
{
InitializeComponent();
}
private void Download_Click(object sender, EventArgs e)
{
label1.Text = ("Downloading...");
WebClient x = new WebClient();
x.DownloadProgressChanged += new DownloadProgressChangedEventHandler(x_DownloadProgressChanged);
x.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(x_DownloadFileCompleted);
x.DownloadFileAsync(new Uri("http://google.com/"), desktop + "\\index.html");
download.Enabled = false;
}
void x_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
label2.Text = null;
label1.Text = "Download Complete.";
MessageBox.Show("Download Done.", "Done!");
}
public void x_DownloadProgressChanged(Object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
this.Text = ":: Kyle :: " + e.ProgressPercentage + "%";
label2.Text = e.BytesReceived + " bytes saved.";
}
public void unzip(String zFile)
{
Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(zFile);
zip.ExtractProgress += new EventHandler<ExtractProgressEventArgs>(zip_ExtractProgress);
zip.ExtractAll(desktop, ExtractExistingFileAction.OverwriteSilently);
zip.Dispose();
zip = null;
}
public void zip_ExtractProgress(object sender, ExtractProgressEventArgs e)
{
if (e.EventType == ZipProgressEventType.Extracting_EntryBytesWritten)
{
this.label2.Text = e.BytesTransferred.ToString(); //unsafe also?
}
else if (e.EventType == ZipProgressEventType.Extracting_BeforeExtractEntry)
{
this.label3.Text = e.CurrentEntry.FileName; //unsafe
}
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
unzip(desktop + "\\Client.zip");
}
void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
button1.Enabled = true;
MessageBox.Show("Done Unzipping.");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
}
}
How do I fix my text labels? I'm using a backgroundWorker and it works without the labels but when I have em it keeps saying Cross-thread operation not valid: Control 'label3' accessed from a thread other than the thread it was created on.
You should report the progress by calling the BackgroundWorker's ReportProgress method.
Alternatively, you can run on the UI thread by calling BeginInvoke.

BackgroundWorker Not working in VSTO

I have a background worker. Before I invoke the worker I disable a button and make a gif visible. I then invoke the runworkerasync method and it runs fine until comleteion. On the 'RunWorkerCompleted()' I get a cross thread error. Any idea why?
private void buttonRun_Click(object sender, EventArgs e)
{
if (comboBoxFiscalYear.SelectedIndex != -1 && !string.IsNullOrEmpty(textBoxFolderLoc.Text))
{
try
{
u = new UpdateDispositionReports(
Convert.ToInt32(comboBoxFiscalYear.SelectedItem.ToString())
, textBoxFolderLoc.Text
, Properties.Settings.Default.TemplatePath
, Properties.Settings.Default.ConnStr);
this.buttonRun.Enabled = false;
this.pictureBox1.Visible = true;
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
//backgroundWorker1.RunWorkerAsync();
}
catch (Exception ex)
{
MessageBox.Show("Unable to process.\nError:" + ex.Message, Properties.Settings.Default.AppName);
}
}
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
buttonRun.Enabled = true;
pictureBox1.Visible = false;
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
u.Execute();
}
It seems to be an issue with VSTO and BackgroundWorker.
The solution is here.
Basically you need to call
System.Threading.SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
before you call RunWorkerAsync. Works great.
To avoid instantiating the object every time you may have a static member in you AddIn's main class and reuse it. This way you only instantiate once.
something about VSTO running the background worker on the same thread as the controls. Not sure. I had to check the InvokeRequired
private void buttonRun_Click(object sender, EventArgs e)
{
if (comboBoxFiscalYear.SelectedIndex != -1 && !string.IsNullOrEmpty(textBoxFolderLoc.Text))
{
try
{
u = new UpdateDispositionReports(
Convert.ToInt32(comboBoxFiscalYear.SelectedItem.ToString())
, textBoxFolderLoc.Text
, Properties.Settings.Default.TemplatePath
, Properties.Settings.Default.ConnStr);
this.buttonRun.Enabled = false;
this.pictureBox1.Visible = true;
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
//backgroundWorker1.RunWorkerAsync();
}
catch (Exception ex)
{
MessageBox.Show("Unable to process.\nError:" + ex.Message, Properties.Settings.Default.AppName);
}
}
}
delegate void ReenableRunCallback();
private void ReenableRun()
{
if (this.buttonRun.InvokeRequired)
{
ReenableRunCallback r = new ReenableRunCallback(ReenableRun);
this.buttonRun.Invoke(r, null);
}
else
this.buttonRun.Enabled = true;
}
private void HideProgress()
{
if (this.pictureBox1.InvokeRequired)
{
ReenableRunCallback r = new ReenableRunCallback(HideProgress);
this.pictureBox1.Invoke(r, null);
}
else
this.pictureBox1.Visible = false;
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
ReenableRun();
HideProgress();
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
u.Execute();
}

Categories

Resources