NESHOM
NESHOM

Reputation: 929

Multiple backgroundworkers calling same function with different parameters

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.

Upvotes: 1

Views: 649

Answers (2)

gerrod
gerrod

Reputation: 6637

Are the parameters from each Background Worker effectively "constant"? If so, you could create a function which returns a function - its similar to the solution you've come up with but more elegant because you don't actually need to make copies of the function. Here's a trivial example:

public void RunBackgroundWorkerOne()
{
    var myFunction = CreateFunction("Hello ", "World");

    while (true)
        myFunction();
}

public Func<string> CreateFunction(string value1, string value2)
{
    return (value1, value2) =>
    {
        return String.Format(value1, value2);
    };
}

Then each background worker gets its own copy of the function built around the parameters that it wants to use.

Depending on how complex the parameters are for the function you're creating, you may want to create a "parameter map" type of class to make the code clearer.

Upvotes: 0

Mike Burdick
Mike Burdick

Reputation: 838

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.

Upvotes: 1

Related Questions