I create multiple BackgroundWorker within a for-loop and each of them needs to know a special value. To simplify, it is just i in this example. When the BackgroundWorker is finished, I need to read that i again. I thought of subclassing BackgroundWorker and creating a class MyBW for that purpose which is able to store the i as value.
My example below works, but I am interested, if this is the best way to do this?
Edit: I have to add, that the variable I need to pass is a simple String, not a large object.
Fully working minimal example
using System;
using System.Text;
namespace MultiThreadTest
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
MyBW bw = new MyBW();
bw.value = i;
bw.WorkerReportsProgress = false;
bw.DoWork += delegate(object sender, System.ComponentModel.DoWorkEventArgs eargs)
{
Console.WriteLine(String.Format("Thread {0} started", bw.value));
System.Threading.Thread.Sleep(bw.value * 1000);
};
bw.RunWorkerCompleted += delegate(object sender, System.ComponentModel.RunWorkerCompletedEventArgs eargs)
{
Console.WriteLine(String.Format("Thread {0} finished", bw.value));
};
bw.RunWorkerAsync();
}
// Only as a run loop that I can see the output.
while (true)
{
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Sleeping...");
}
}
}
class MyBW : System.ComponentModel.BackgroundWorker
{
/// <summary>
/// Here I store the value.
/// </summary>
public int value;
}
}
async/awaitbut let's wait for someone who can ;-D \$\endgroup\$Task,BackgroundWorkerare really oldschool. blog.stephencleary.com/2012/02/… \$\endgroup\$