I have a C# ASP.NET MVC project.
I am basically running a simulation (with an option to cancel) and collating the results.
I need to use multi-threading as I could run a million or more simulations at at time.
My code is like this:
public class MyClass
{
private ConcurrentBag<StuffResult> StuffResults { get; set; }
private bool CancellationRequested { get; set; }
public void DoAlotOfStuff(int numberOfStuffToDo)
{
var cancellationTokenSource = new CancellationTokenSource();
var options = new ParallelOptions { CancellationToken = cancellationTokenSource.Token };
Task.Factory.StartNew(() =>
{
if (CancellationRequested) cancellationTokenSource.Cancel();
});
try
{
Parallel.For(0, numberOfStuffToDo, options, a =>
{
options.CancellationToken.ThrowIfCancellationRequested();
var class1 = new Class1();
var class2 = new Class2();
var class3 = new Class3();
var class4 = new Class4(class1, class2, class3);
var result = class4.DoStuff();
StuffResults.Add(result);
});
}
catch (OperationCanceledException e)
{
//handle exception
}
}
}
Question: How can I avoid instantiating a new Class1, Class2, Class3, and Class4 object for each iteration? I read this msdn article but I don't understand it. Perhaps 1 of each object per thread.
It look safe enough to me...
If the classes have some kind of state involved with them then I don't know if you can avoid instantiating them. If not, you might be able to declare the classes outside the loop or make the DoStuff method static so you don't need an instantiated class at all.