I have been trying to implement a BackgroundWorker into my application, and so far, it has not gone well. On a new thread, I want to open up a new Form that will have a progressbar and a label to report progress, however, this is not working well. When I call ShowDialog, the application does not respond any more. Is this because my code is running from my Form1, and I am showing WorkingForm? Also, can this be implemented cleaner?
private void button14_Click(object sender, EventArgs e)
{
List<object> param = new List<object>();
object[] objectparams = new object[1];
objectparams[0] = null;
Opera opera = new Opera();
System.Reflection.MethodInfo clearOpera = opera.GetType().GetMethod("ClearOpera");
param.Add(clearOpera);
param.Add(opera);
param.Add(objectparams);
backgroundWorker1.RunWorkerAsync(param);
}
private void button2_Click_1(object sender, EventArgs e)
{
Browser.cancelPending = true;
}
private delegate void getnewform();
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
mainForm main = new mainForm();
TestURLGUI4.Form1 form = (TestURLGUI4.Form1)Application.OpenForms[0];
var variab = (bool)form.Invoke(new getnewform(main.AskForConfirmation));
List<object> param = e.Argument as List<object>;
List<object> result = new List<object>();
var method = param[0] as MethodInfo;
object[] parameters = param[2] as object[];
if (parameters[0] == null)
{
result.Add(method.Invoke(param[1], null));
result.Add(false);
}
else
{
result.Add(method.Invoke(param[1], parameters));
if (parameters.Contains(true))
result.Add(true);
}
int progress = (100 * Browser.progressValue) / Browser.progressMax;
backgroundWorker1.ReportProgress(progress);
// If the BackgroundWorker.CancellationPending property is true, cancel
if (backgroundWorker1.CancellationPending)
{
Console.WriteLine("Cancelled");
Browser.cancelPending = true;
}
e.Result = result;
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
TestURLGUI4.WorkingForm form = (TestURLGUI4.WorkingForm)Application.OpenForms[1];
form.progressBar1.Value = e.ProgressPercentage;
form.label1.Text = Browser.progressValue + "/" + Browser.progressMax;
Application.DoEvents();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
List<object> param = e.Result as List<object>;
if (e.Cancelled == false && param.Contains(true))
{
Display.DisplayURLs(param[0] as SortableBindingList<URL>);
TestURLGUI4.WorkingForm form = (TestURLGUI4.WorkingForm)Application.OpenForms[1];
MessageBox.Show("Done");
}
else if (e.Cancelled == false && param.Contains(false))
{
TestURLGUI4.WorkingForm form = (TestURLGUI4.WorkingForm)Application.OpenForms[1];
MessageBox.Show("Done");
}
}
public class mainForm
{
public void AskForConfirmation()
{
TestURLGUI4.Form1 form = (TestURLGUI4.Form1)Application.OpenForms[0];
var workingForm = new TestURLGUI4.WorkingForm();
workingForm.ShowDialog(form);
workingForm.DialogResult = DialogResult.None;
}
}
Edit:
Ok, I have updated my code according to the suggestions, and now, this produces a stackoverflowexception in System.Windows.Forms.dll:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
mainForm main = new mainForm();
TestURLGUI4.Form1 form = (TestURLGUI4.Form1)Application.OpenForms[0];
List<object> param = e.Argument as List<object>;
List<object> result = new List<object>();
var method = param[0] as MethodInfo;
object[] parameters = param[2] as object[];
if (parameters[0] == null)
{
result.Add(method.Invoke(param[1], null));
result.Add(false);
}
else
{
result.Add(method.Invoke(param[1], parameters));
if (parameters.Contains(true))
result.Add(true);
}
int progress = (100 * Browser.progressValue) / Browser.progressMax;
backgroundWorker1.ReportProgress(progress);
// If the BackgroundWorker.CancellationPending property is true, cancel
if (backgroundWorker1.CancellationPending)
{
Console.WriteLine("Cancelled");
Browser.cancelPending = true;
}
e.Result = result;
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
TestURLGUI4.Form1 form1 = (TestURLGUI4.Form1)Application.OpenForms[0];
if (Application.OpenForms.Count >= 2)
{
TestURLGUI4.WorkingForm form2 = (TestURLGUI4.WorkingForm)Application.OpenForms[1];
form2.progressBar1.Value = e.ProgressPercentage;
form2.label1.Text = Browser.progressValue + "/" + Browser.progressMax;
Application.DoEvents();
}
else if(Application.OpenForms.Count == 1)
{
var workingForm = new TestURLGUI4.WorkingForm();
workingForm.ShowDialog(form1);
}
}
The purpose of a BackgroundWorker is to invoke code on another thread (not the UI thread). By calling Invoke in the DoWork method, you're completely circumventing the purpose of BackgroundWorker. Do all your UI work before you start the worker. If you need to interact with the user while the worker is working, do it in the ProgressChanged handler--it runs on the UI thread and you don't need to use Invoke in ProgressChanged.
By invoking UI work in DoWork, you run the risk of a deadlock, which will hang your program
you cant run UI on other threads. Has to be on the main thread.
Instantiate the UI before you start the new thread. In the new thread use cross thread invoke methods on the controls you want to work with. Look here for example http://msdn.microsoft.com/en-us/library/ms171728.aspx
Related
I'm starting to work with BackgroundWorker to try it out, and I'm wondering how can I stop a query which returns an Object List and that may take some time to execute.
I guess that I can't stop the query on the server, but what I'm specifically looking for is to stop the read of the SqlDataReader which contains the result of this query.
Here's a code sample with my BackgroudnWorker and a sample query :
public partial class Form1 : Form
{
private BackgroundWorker worker;
public Form1 (Point location)
{
this.Location = location;
InitializeComponent();
worker = new BackgroundWorker
{
WorkerSupportsCancellation = true,
};
worker.DoWork += this.Worker_DoWork;
worker.RunWorkerCompleted += this.Worker_RunWorkerCompleted;
}
#region Form
private void ButtonBack_Click (object sender, EventArgs e)
{
if (worker.IsBusy && !worker.CancellationPending)
{
worker.CancelAsync();
}
this.Close();
}
private void TextBoxSearch_TextChanged (object sender, EventArgs e)
{
while (worker.IsBusy)
{
if (worker.IsBusy && !worker.CancellationPending)
{
worker.CancelAsync();
}
}
worker.RunWorkerAsync();
}
#endregion
#region Worker
private void Worker_RunWorkerCompleted (object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
if (worker.IsBusy && !worker.CancellationPending)
{
worker.CancelAsync();
}
Console.WriteLine(e.Error.Message);
}
}
private void Worker_DoWork (object sender, DoWorkEventArgs e)
{
if (!worker.CancellationPending)
{
// Where I'd like to cut the IEnumerable if worker.CancellationPending to shorten time of process
foreach (LigneHS ligne in GetLignesHS(worker.CancellationPending))
{
if (worker.CancellationPending)
{
e.Cancel = true;
return;
}
// Do work
}
}
else
{
e.Cancel = true;
return;
}
}
#endregion
// Sample query
internal static IEnumerable<LigneHS> GetLignesHS (bool cancellationPending)
{
string requete = "SELECT * FROM [MY_TABLE] ORDER BY [date] DESC";
SqlConnection conn = BDD.OpenBDD16();
SqlCommand command = new SqlCommand(requete, conn);
List<LigneHS> lignes = new List<LigneHS>();
LigneHS ligne = new LigneHS();
try
{
if (!cancellationPending)
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read() && !cancellationPending)
{
ligne = new LigneHS();
if (reader["id"] != DBNull.Value)
{
ligne.Id = Convert.ToInt32(reader["id"]);
// filtering null values for every column
lignes.add(ligne);
// tried to add the yield return here, but can't inside a try-catch
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("GetLignesHS : " + ex.Message);
}
finally
{
command.Dispose();
conn.Close();
}
return lignes;
}
}
As it is here, cancellationPending of the query doesn't update if the worker is asked to stop.
I first thought of using a yield return to interrupt the foreach if the BackgroundWorker is asked to stop. But, I'm using a try-catch in the treatment of the query, so I can't.
I know that using a CancellationToken as I did when I used straight thread will work, but I wonder if it is the best way to achieve what I want here.
I have a method in my class that has some loops inside.
Main purpose of this method is converting some files so I put a progressbar in my form that should get updated after each file has been converted.
I tried every possible combination and I read everything I could but I couldn't solve this issue.
void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
converterProgressBar.Value = e.ProgressPercentage;
}
is called only after the main loop of my method has been executed.
This is my method:
public string Convert()
{
convertBtn.Enabled = false;
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
totalCount = files.length;
bw.RunWorkerAsync();
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
foreach (string file in files)
{
countFile++;
if (chk.Checked)
{
class1.DoJob();
}
using (// some code))
{
using (//some other code))
{
try
{
using (// again some code)
{
// job executing
}
}
catch (exception
{
}
}
}
convertedVideosL.Text = txtToUpdate;
convertedVideosL.Refresh();
}
countFile = countFile + 1;
MessageBox.Show("Done");
countFile = -1;
return outputFile;
}
And here are the BackgroundWorker Event Handlers:
void bw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i <= totalCount; i++)
{
if (bw.CancellationPending)
{
e.Cancel = true;
}
else
{
int progress = Convert.ToInt32(i * 100 / totalCount);
(sender as BackgroundWorker).ReportProgress(progress, i);
}
}
}
void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
converterProgressBar.Value = e.ProgressPercentage;
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == false)
{
convertedVideosL.Text = "Finished!";
}
else
{
convertedVideosL.Text = "Operation has been cancelled!";
}
}
But I cannot get to update the progress bar for every file that is converted.
It waits for the foreach loop to end and then calls bw_ProgressChanged.
If I put RunWorkerAsync() inside the foreach loop an exception is thrown that says the BackgroundWorker is busy and cannot execute other tasks.
It seems to me obvious that DoWork() only executes a for loop then it shouldn't be aware of the conversion going on but ProgressChanged should be fired by ReportProgress(progress,i).
Could please someone explain me why and help me with a solution?
Thanks!
Currently the conversion is not executed by the instance of the BackgroundWorker type. The conversion should be called from the DoWork event handler.
Please consider extracting the conversion-related functionality:
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
foreach (string file in files)
{
// Details...
}
into the separate method. After that just call the method from the DoWork event handler.
Pseudo-code to demonstrate the idea:
public void StartConversion()
{
...
TWorkerArgument workerArgument = ...;
worker.RunWorkerAsync(workerArgument);
// No message box here because of asynchronous execution (please see below).
}
private void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
{
// Get the BackgroundWorker that raised this event.
BackgroundWorker worker = sender as BackgroundWorker;
e.Result = Convert(worker, (TWorkerArgument)e.Argument);
}
private static TWorkerResult Convert(BackgroundWorker worker, TWorkerArgument workerArgument)
{
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
foreach (string file in files)
{
// Details...
worker.ReportProgress(percentComplete);
}
return ...;
}
private void BackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Show the message box here if required.
}
Please replace the TWorkerArgument and TWorkerResult types appropriately.
Also, please refer to the example which uses the BackgroundWorker class for the additional details: How to: Implement a Form That Uses a Background Operation, MSDN.
I am working on a MDI app where the user can create multiple instances of the same form (call it ListForm). Each instance of the ListForm has a flowlayoutpanel containing a unique set of user controls. The ListForm also contains a StatusStrip ProgressBar and a button called 'ReadAll'.
Each user control has a 'Read' button that will perform a read operation when clicked. This operation can take up to 3 seconds to complete.
What I am trying to do is when the user clicks the 'ReadAll' button, the childform spawns a background thread the iterates through the flowlayoutpanel.controls collection and invokes each user controls .PerformClick() method. This updates all the usercontrols in the form.
The problem is that it looks like the event handler for all instances of the form is being called resulting in all user controls in all instances of the ListForm are being updated. Additionally, when I ReportProgress from the backgroundworker, all the progressbars for all instances of the ListForm are updated. This functionality is not desired.
How can I ensure that only the ListForm that spawned the backgroundworker is updated? Is there a preferred way to uniquely identify the child form?
Thanks in advance for your help. Code is below...
public partial class ListForm: Form
{
// Background Worker Thread for Read / Write All tasks
private static BackgroundWorker bw = new BackgroundWorker();
public ListForm()
{
InitializeComponent();
// Configure the Background Worker that reads and writes all variable data
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
private void btnReadAll_Click(object sender, EventArgs e)
{
if (bw.IsBusy != true)
{
// Start the ReadAll parameters thread
btnReadAll.Text = "Cancel Read";
btnWriteAll.Enabled = false;
bw.RunWorkerAsync("R");
}
else if (bw.WorkerSupportsCancellation == true)
{
// Cancel the ReadAll parameters thread
bw.CancelAsync();
}
}
// ****************************** Background Thread Methods ***************************
public delegate void DoUIWorkHandler();
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
DoUIWorkHandler DoReadClick;
DoUIWorkHandler DoWriteClick;
int CurrentControlCount = 1;
string StatusText = "";
int ProgressValue = 0;
string argument = e.Argument as string;
// *******************Perform a time consuming operation and report progress.
try
{
foreach (UserControl c in this.flowLayoutPanel1.Controls)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
// Update the status and return it to the UI
StatusText = "Updating: (" + (CurrentControlCount).ToString() + " of " + flowLayoutPanel1.Controls.Count.ToString() + ") " + c.ParamProperties.strDHIndexDescription;
ProgressValue = (int)(((float)CurrentControlCount / (float)flowLayoutPanel1.Controls.Count) * 100);
worker.ReportProgress(ProgressValue, StatusText);
System.Threading.Thread.Sleep(20);
CurrentControlCount++;
// Update the contorl
if (c.InvokeRequired)
{
if (argument == "R")
{
DoReadClick = c.btnRead.PerformClick;
c.Invoke(DoReadClick);
}
else
{
DoWriteClick = c.btnWrite.PerformClick;
c.Invoke(DoWriteClick);
}
}
}
}
}
catch(InvalidCastException ex)
{
// Catch any functions that are in the Layout panel
string ErrorStr = "Could not cast a Function control to a Parameter control. \n\r\r Exception: " + ex.Message;
srvcAppLogger.Logger.Log(new clsApplicationLogger.LoggerMessage(ErrorStr, "bw_DoWork", "frmVariableHandlerGUI"));
}
catch (Exception ex)
{
string ErrorStr = "An unecpected exception occured. Error: " + ex.Message.ToString();
srvcAppLogger.Logger.Log(new clsApplicationLogger.LoggerMessage(ErrorStr, "bw_DoWork", "frmVariableHandlerGUI"));
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.tsStatus.Text = e.UserState.ToString();
this.tsProgressBar.Value = e.ProgressPercentage;
}
You've one instance of BackgroundWorker and each ListForm you create, is registered to this worker. So you've to pass the instance of the Form to the worker.
Create a little Helper class with two Attributes. This is just an example. You could also pass an identifier or what ever you like:
public struct ReadAllArguments
{
public bool Read;
public ListForm CallingForm;
public ReadAllArguments(bool read, ListForm callingForm)
{
Read = read; CallingForm = callingForm;
}
}
You could pass it then like this:
...
if (bw.IsBusy != true)
{
// Start the ReadAll parameters thread
btnReadAll.Text = "Cancel Read";
btnWriteAll.Enabled = false;
bw.RunWorkerAsync(new ReadAllArguments(true, this));
}
...
An later read it like that:
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
DoUIWorkHandler DoReadClick;
DoUIWorkHandler DoWriteClick;
int CurrentControlCount = 1;
string StatusText = "";
int ProgressValue = 0;
ReadAllArguments arguments = e.Argument as ReadAllArguments;
if (this != arguments.ListForm)
return;
...
if (arguments.Read)
{
DoReadClick = c.btnRead.PerformClick;
c.Invoke(DoReadClick);
}
else
{
DoWriteClick = c.btnWrite.PerformClick;
c.Invoke(DoWriteClick);
}
...
You'll realize that you can even move the Work-Method out of you Form because there are no direct dependencies and you don't need access to the "this"-Qualifier. You've passed everything in you argument. After replacing every "this" by that argument you could register exactly one Work-Method to the DoWork-Event of your Worker. This would be much cleaner and more elegant...
Here's an example how you could do this:
public partial class ListForm: Form
{
// Background Worker Thread for Read / Write All tasks
private static BackgroundWorker bw = new BackgroundWorker();
static ListForm()
{
//We move the do-work out of the instance constructor, because the work that has to be done, is not connected to our instances. So we've only one definition of our work that has to be done
bw.DoWork += new DoWorkEventHandler(TheWorkThatHasToBeDone);
}
public ListForm()
{
InitializeComponent();
// Configure the Background Worker that reads and writes all variable data
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
//no more registering on instance level
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
//Your new instance-independent doWork-Method - static here
private static void TheWorkThatHasToBeDone(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
ReadAllArguments arguments = e.Argument as ReadAllArguments;
//You call the instance-Method here for your specific instance you want the work to be done for
arguments.ListForm.bw_DoWork(worker, arguments);
}
//Your old bw_DoWork-Method with nicer arguments - you should change the method name...
private void bw_DoWork(BackgroundWorker worker, ReadAllArguments arguments)
{
DoUIWorkHandler DoReadClick;
DoUIWorkHandler DoWriteClick;
int CurrentControlCount = 1;
string StatusText = "";
int ProgressValue = 0;
// *******************Perform a time consuming operation and report progress.
try
{
...
}
}
It would again be more elegant to move the stuff out of the forms code and not doing this with static members, but I think the idea is clear.
To identify object you could use HashCode or create an Id property, and next use it in custom EventArgs.
private Guid _controlId;
public ListForm()
{
_controlId = Guid.NewGuid();
...
}
Try also to menage the event observators in this way:
private void btnReadAll_Click(object sender, EventArgs e)
{
if (bw.IsBusy != true)
{
bw.DoWork += bw_DoWork;
bw.ProgressChanged += bw_ProgressChanged);
bw.RunWorkerCompleted +=bw_RunWorkerCompleted;
// Start the ReadAll parameters thread
btnReadAll.Text = "Cancel Read";
btnWriteAll.Enabled = false;
bw.RunWorkerAsync("R");
}
else if (bw.WorkerSupportsCancellation == true)
{
// Cancel the ReadAll parameters thread
bw.CancelAsync();
}
bw.DoWork -= bw_DoWork;
bw.ProgressChanged -= bw_ProgressChanged;
bw.RunWorkerCompleted -= bw_RunWorkerCompleted;
}
I have a C# winform application which needs to run multiple instance in synchronous way. The goal is to:
If the exe runs 3 times, it runs the first instance of the exe and the rest will wait until the first instance finishes the processing. Then, a next waiting exe intance will run and process and so on.
The exe will run one by one until it finish processing then the exe will terminates automatically af.
Any idea how to do this?
I already tried below:
private void CheckInstance()
{
bool _returnValue = true;
string _lockFile = string.Empty;
Random _rnd = new Random();
int _randomValue = _rnd.Next(100, 200);
int _rndmiliSec = 0;
_rndmiliSec = DateTime.Now.Millisecond * _rnd.Next(2, 6);
_lockFile = string.Concat(AppDomain.CurrentDomain.BaseDirectory, string.Format("/{0}", instanceFileName));
while (_returnValue)
{
_returnValue = File.Exists(_lockFile);
if (_returnValue)
{
Thread.Sleep(1000);
this.Hide();
}
else
{
try
{
Thread.Sleep((_rnd.Next(1000) + _rndmiliSec) + _rnd.Next(1000, 1500));
Functions.WriteLog(_lockFile, "Starting the process...");
Functions.WriteLog(_lockFile, string.Format("Start Time : {0}", paramPrintTime));
File.SetAttributes(_lockFile, FileAttributes.ReadOnly);
this.Show();
break;
}
catch (Exception)
{
_returnValue = false;
}
}
}
}
private void DeleteInstance()
{
try
{
File.SetAttributes(string.Concat(AppDomain.CurrentDomain.BaseDirectory, string.Format("/{0}", instanceFileName)), FileAttributes.Normal);
File.Delete(string.Concat(AppDomain.CurrentDomain.BaseDirectory, string.Format("/{0}", instanceFileName)));
}
catch (Exception)
{
}
}
private void Form_Shown(Object sender, EventArgs e)
{
_backWorker.RunWorkerAsync();
}
private void FormClosed(object sender, FormClosedEventArgs e)
{
DeleteInstance();
}
private void Form_Load(object sender, System.EventArgs e)
{
CheckInstance();
}
BackgroundWorker _backWorker = new BackgroundWorker();
public Form()
{
InitializeComponent();
_backWorker.WorkerReportsProgress = true;
_backWorker.ProgressChanged += _backWorker_ProgressChanged;
_backWorker.RunWorkerCompleted += _backWorker_RunWorkerCompleted;
_backWorker.DoWork += _backWorker_DoWork;
}
private void _backWorker_DoWork(object sender, DoWorkEventArgs e)
{
Do some work processing...
}
private void _backWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();
}
private void _backWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pg.Value = e.ProgressPercentage;
lblIndicator.Text = e.UserState.ToString();
}
When the exe run 3 instance, the first instance will run while 2nd and third hides for a while awaiting the 1st instance to be finisih. However, after the 1st instance finish the process, The 2nd and 3rd instance are running simultaneously.
Any Ideas? Thanks.
Maybe this can work:
public static bool IsProgramRunning(string TitleOfYourForm)
{
bool result = false;
Process[] processes = Process.GetProcesses();
foreach (Process p in processes)
{
if (p.MainWindowTitle.Contains(TitleOfYourForm))
{
result = true;
break;
}
}
return result;
}
Call this function in the Main function(before opening the mainForm), if it is false Application.Exit() else show your form..
If this answer helped you, vote me.
i call this after a button click:
FORM1-Code:
{
ProgressBar.Maximum = 500;
myArguments gifargs = new myArguments(); //class for passing arguments to the bgW
gifargs.InputFilePath = listBox1.SelectedItem.ToString(); // input filepath
gifargs.OutputFilePath = saveFileDialog1.FileName; //output filepath
backgroundWorker1.RunWorkerAsync(gifargs); // run bgW async with args
}
// here is bgW doWork
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
myArguments args = e.Argument as myArguments; //myArguments class
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
}
PictureHandler makeAnimatedGIf = new PictureHandler(); // creating new object
makeAnimatedGIf.imageGif(args.InputFilePath,args.OutputFilePath); //call method with args
makeAnimatedGIf.GifProgress += new PictureHandler.myprogressgetter(this.GifProgressF1);
//add the delegate
works perfect until here
this is my Callback function which should update bgW.ReportProgress
but it never gets there?!
private void GifProgressF1(int i)
{
System.Threading.Thread.Sleep(500);
backgroundWorker1.ReportProgress(i);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
ProgressBar.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
ProgressBar.Value = 0;
if (e.Cancelled)
{
MessageBox.Show("Process canceled!");
}
else
{
MessageBox.Show("Process complete!");
}
}
<----Picturehandler.cs-Code----->
//Delegate definition in my Picturehandler class
public delegate void myprogressgetter(int i);
public myprogressgetter GifProgress;
public void imageGif(string input, string output)
{
Process imagemagick = new Process();
imagemagick.StartInfo.FileName = "convert.exe";
imagemagick.StartInfo.Arguments = "-monitor -delay 1 " + input + " +map " + output;
imagemagick.EnableRaisingEvents = false;
imagemagick.StartInfo.UseShellExecute = false;
imagemagick.StartInfo.CreateNoWindow = true;
imagemagick.StartInfo.RedirectStandardOutput = true;
imagemagick.StartInfo.RedirectStandardError = true;
imagemagick.Start();
StreamReader ima = imagemagick.StandardError;
bool assign2 = false;
do
{
string consolausgabe = ima.ReadLine();
if (consolausgabe.Contains("Reduce") == true)
{
assign2 = true;
}
gifprocess(consolausgabe, assign2);
} while (!ima.EndOfStream);
imagemagick.WaitForExit();
imagemagick.Close();
}
private void gifprocess(string cline, bool zähl)
{
if (cline.Contains("Load"))
{
string a1 = cline;
string[] a11 = a1.Split(new char[] { ':', ',' });
string a12 = a11[3];
string[] a13 = a12.Split(new char[] { '%' });
int load1 = Convert.ToInt32(a13[0]);
GifProgress(load1;) //<<<<<------------- this will give me an exception
// Visual Studio says GifProgress = null in Autos
}
now if i call GifProgress(100) or any other integer, I get exception(Object reference not set to an instance of an object.), progressbar gets never updated.
The progress information from the picturehandler class wont get to the UI, I tried for 2 days now.
I use same code to get textbox.text from form2 and callback function works just fine.
WorkerReportProgress = TRUE.
Typically, your DoWork method would have a loop in it. Each iteration of the loop could finish with a call to ReportProgress, which would cause the stuff in ProgressChanged to run.
Since you're just running a few lines of code, use the RunWorkerCompleted to set the progress indicator and forget ReportProgress altogether.
Here's a tutorial I used to understand the BackgroundWorker better, if it helps...
Unless maybe you're doing what you're doing because your background worker thread exits before makeAnimatedGIf.imageGif is finished doing whatever it does...
Make sure your BackgroundWorker's WorkerReportsProgress property is set to true. Default is false
Make sure to set WorkerReportsProgress to true and use Invoke() to update the progressbar from another thread.
The function that you expect to be called, GifProgressF1 is only referenced as a call back for an instance of `PictureHandler' class. Where and how this call back is called in entirely up to that class then. However from your description it is not clear where this class comes from or what it does. I'd suggest referring either to the class documentation or source code, to find exactly when this callback is supposed to be called and going from there.