I've a question about multithreading
in C#.
Let's suppose we have this interface
public interface IMyCallback
{
void OnSum(int a, int b, int result);
}
Then I've another class, that has a list of IMyCallback
as private field
public class MyClass
{
private IList<IMyCallback> _Subscribers = new List<IMyCallback>();
public void Sum(int a, int b)
{
int result = a + b;
foreach (IMyCallback subscriber in _Subscribers)
{
subscriber.OnSum(a, b, result);
}
}
}
Pratically what it does is doing a sum between two numbers and notify all the service subscribers that it has performed the arithmetic operation a + b
and the result is result.
Now I want to improve the performance and send each notification onto a Thread. What I usually do to avoid enclosure and memory problem with compiler is this:
public void Sum (int a, int b)
{
int result = a + b;
foreach (IMyCallback subscriber in _Subscribers)
{
new Thread((o) =>
{
object[] state = (object[])o;
((IMyCallback)state[0])
.OnSum((int)state[1], (int)state[2], (int)state[3]
})
{
IsBackground = true
}
.Start(new object[] { subscriber, a, b, result });
}
}
I want to focus the attention on the last part, when I pass all the parameters into an array of object and use it into the delegate. Am I doing correct? Is it a correct pattern or there are some issues I cannot understand?