I am learning to program in C# and have most of the basics down already. I am having trouble using the background worker and using it with multiple classes. This is a backup pro
Instead of using BackgroundWorker as-is, consider inheriting from it. This gives you more flexibility about how you get data in and out. Consider this example, where you pass in data in the constructor and get it out with a property:
class BackgroundDoerOfSomething : BackgroundWorker
{
string _SomeData;
public string SomeResult { get; private set; }
public BackgroundDoerOfSomething(string someData)
{
_SomeData = someData;
}
protected override void OnDoWork(DoWorkEventArgs e)
{
base.OnDoWork(e);
// do some processing, and then assign the result
SomeResult = "some other data";
}
}
You would use it like this:
class DoSomethingInBackground
{
BackgroundDoerOfSomething _doer;
void DoSomething()
{
_doer = new BackgroundDoerOfSomething("abc");
_doer.RunWorkerCompleted += _doer_RunWorkerCompleted;
_doer.RunWorkerAsync();
}
void _doer_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
var myResult = _doer.SomeResult;
// then do something with the result
}
}