I am trying to understand what I can and cant do with background workers. I have seen a fair amount of posts on this but it all seems to involve some operation with loops and you cancel an operation within a loop. I am wanting to find out if I can cancel some operation on a background worker without a loop.
I have the following simple form that I'm playing with:
which contains the following code:
string[,] TestData = new string[300000, 100];
List<string> TestDataList;
private static Random random = new Random();
public Form1()
{
InitializeComponent();
// Loading up some fake data
for (int i = 0; i < 300000; i++)
{
for (int j = 0; j < 100; j++)
{
this.TestData[i, j] = RandomString(10) + j.ToString();
}
}
}
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
which loads a string array with a lot of dummy data. The start button method is as follows:
private void StartWork_Click(object sender, EventArgs e)
{
try
{
System.Threading.SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_Complete);
bw.RunWorkerAsync();
}
catch (Exception ex)
{
MessageBox.Show("Something went wrong.\nError:" + ex.Message);
}
}
And I also have:
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
this.TestDataList = this.TestData.Cast<string>()
.Select((s, i) => new { GroupIndex = i / 100, Item = s.Trim().ToLower() })
.GroupBy(g => g.GroupIndex)
.Select(g => string.Join(",", g.Select(x => x.Item))).ToList();
}
private void bw_Complete(object sender, RunWorkerCompletedEventArgs e)
{
this.showWorkingLabel.Text = "Work done";
}
private void btnCancel_Click(object sender, EventArgs e)
{
// I want to cancel the work with this button
// Then show
this.showWorkingLabel.Text = "Work Cancelled";
}
So you'll notice that my bw_DoWork
method does not contain any loops, just a single operation and I want to know if:
- If I can kill/cancel the background worker by clicking the Cancel button while the following code is being executed:
.Select((s, i) => new { GroupIndex = i / 100, Item = s.Trim().ToLower() })
.GroupBy(g => g.GroupIndex)
.Select(g => string.Join(",", g.Select(x => x.Item))).ToList();
- Can I update the label
showWorkingLabel
while the background work is happening so that it continuously shows".", "..", "..."
and then back to"."
like a progress bar to indicate work is still happening