I have found an article on this subject but I can't quite get my head around how to implement the answer proposed.
What I am getting is a cross-thread exception and I realise that the GUI is in one thread and the worker is in another thread. The exception:
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Cross-thread operation not valid: Control 'listBoxCodes' accessed from a thread other than the thread it was created on.
Source=System.Windows.Forms
StackTrace:
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.SendMessage(Int32 msg, Int32 wparam, String lparam)
at System.Windows.Forms.ListBox.NativeInsert(Int32 index, Object item)
at System.Windows.Forms.ListBox.ObjectCollection.AddInternal(Object item)
at System.Windows.Forms.ListBox.ObjectCollection.Add(Object item)
at Find_Duplicate_MX_codes.MyThread.backgroundWorker_DoWork(Object sender, DoWorkEventArgs e) in D:\My Programs\Find Duplicate MX codes\Find Duplicate MX codes\MyThread.cs:line 69
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
InnerException:
Now, I was trying to initially to deal with this by writing my code as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Find_Duplicate_MX_codes
{
public struct ThreadSettings
{
public Find_Duplicate_MX_codes.Form1 pMainForm { get; set; }
public ProgressBar progressBar { get; set; }
public TextBox progressLabel { get; set; }
public String strFile { get; set; }
public ListBox lbCodes { get; set; }
public ListBox lbCodesDuplicate { get; set; }
}
class MyThread
{
private BackgroundWorker m_backgroundWorker;
ThreadSettings m_sThreadSettings;
public MyThread(ThreadSettings sThreadSettings)
{
m_sThreadSettings = sThreadSettings;
m_backgroundWorker = new BackgroundWorker();
m_backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
m_backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
m_backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
m_backgroundWorker.WorkerReportsProgress = true;
}
public void start()
{
if(m_sThreadSettings.pMainForm != null)
m_sThreadSettings.pMainForm.Enabled = false; // Stop user interacting with the form
m_backgroundWorker.RunWorkerAsync();
}
public void stop()
{
m_backgroundWorker.CancelAsync();
}
public void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
m_backgroundWorker.ReportProgress(0, "Extracting MX codes {0}%)");
using (var reader = new StreamReader(m_sThreadSettings.strFile))
{
Stream baseStream = reader.BaseStream;
long length = baseStream.Length;
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.Length > 8 && line.Substring(0, 4) == "080,")
{
string strCode = line.Substring(4, 4);
if (m_sThreadSettings.lbCodes.FindStringExact(strCode) == -1)
{
m_sThreadSettings.lbCodes.Items.Add(strCode);
}
else
m_sThreadSettings.lbCodesDuplicate.Items.Add(strCode);
}
m_backgroundWorker.ReportProgress(Convert.ToInt32(baseStream.Position / length * 100), "Extracting MX codes {0}%)");
}
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if(m_sThreadSettings.progressBar != null)
m_sThreadSettings.progressBar.Value = e.ProgressPercentage;
if(m_sThreadSettings.progressLabel != null)
m_sThreadSettings.progressLabel.Text = String.Format((string)e.UserState, e.ProgressPercentage);
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
int iResult = Convert.ToInt32(e.Result);
if (m_sThreadSettings.pMainForm != null)
m_sThreadSettings.pMainForm.Enabled = true; // User can interact with form again
}
}
}
If I comment out the line of code that tries to add an item to the list box is works. Progress bar/label are updating. It is when I try to update the listbox that it fails.
In the answer on the other post it suggests:
UserContrl1_LOadDataMethod()
{
if(textbox1.text=="MyName") //<<======Now it wont give exception**
{
//Load data correspondin to "MyName"
//Populate a globale variable List<string> which will be
//bound to grid at some later stage
if(InvokeRequired)
{
// after we've done all the processing,
this.Invoke(new MethodInvoker(delegate {
// load the control with the appropriate data
}));
return;
}
}
}
But I am struggling to understand how to make use of that answer for my lines of code:
m_sThreadSettings.lbCodes.Items.Add(strCode);
How do I change it so that I can get the list boxes populated and:
a) Not get the cross-thread exception b) Not choke the GUI due to the updating of the list boxes
Thank you!
Update: I have tried this code:
Invoke(new MethodInvoker(delegate { m_sThreadSettings.lbCodes.Items.Add(strCode); }));
But I get warnings that I don't fully understand:
Update 2: I now realise that Invoke is part of the Form object. So I changed my code to:
if (m_sThreadSettings.lbCodes.FindStringExact(strCode) == -1)
m_sThreadSettings.pMainForm.Invoke(new MethodInvoker(delegate { m_sThreadSettings.lbCodes.Items.Add(strCode); }));
else
m_sThreadSettings.pMainForm.Invoke(new MethodInvoker(delegate { m_sThreadSettings.lbCodesDuplicate.Items.Add(strCode); }));
That now seems to work. But watch this animation:
https://www.dropbox.com/s/mznoqhqll8m28x7/Results0001.mp4?dl=0
It just doesn't all process quite as I expect. It seems to still be doing all the processing of the GUI once the reading has finished. Confused.
Update 3: I used Console.Beep() to establish when my progress change handler was being fired. In addition, I confirmed when the progress actually changes. And it does 0 for all apart from towards the end when it does 100. So this BaseSteam.Position might be the fault.