Multiple background agents calling the same function with different parameters

advertisements

I have two backgroundworkers that are calling one function in an infinite while loop but with different input parameters. There are a lot of variables used in that function.

Question: what is the best approach for defining the variables used inside the function?

If I define the variables globally, the performance is great. BUT, I must use lock a lot of times to make sure there is no conflicts when the variables are modified.

If I define the variables locally inside the function, there would be no conflict (obviously), but the code gets 2-3 times slower. This is as expected, because it is just like defining variables inside loop instead of defining them outside the loop.

One solution is to make another copy of that function and define separate global variables for use for the second thread and second function called in that thread. This may be good in terms of performance, but I believe it is not the most elegant approach.

Any opinion/solution is appreciated.


Create a Class that contains Properties for all the variables. Have each BackgroundWorker create their own instance of this class and pass it to the function as a Argument.

Although I'm not quite clear why your performance slows down 2-3 times if you define these variables in the Function itself.