MaXL130 MaXL130 - 2 months ago 10
C# Question

Compare parameters of multiple callbacks

I am programming a game using the Unity Engine and I am currently running into the following problem:

I have a method that asynchronously returns his result using the parameters of a callback function. Pretty straightforward, it looks like this:

public void CalculateSomething( - PARAMETERS - , Action<float> callback)


I have to call this method in a loop for different parameters.

foreach(float f in manyFloats){
CalculateSomething(f, myCallback);
}
void myCallback(float f){
...compare this result value to the other values?...
}


Now I would like to compare the resulting floats, that come with the different callbacks. Let's just say I want to find the highest value among those floats. How do I do that?

I had the idea to store the results in an array field and just compare after it is fully filled, but I don't know who to check if all callbacks are done already.

Ideally I'd like to avoid polluting my class with an field like this, but it would be alright if there is no other way.

The
CalculateSomething
function is part of a library, so I can't change it. Everything else is variable.

Answer

Here is the deal. You got it right about creating the array and storing the values and compare them when all callbacks are done. Hence the problem is that you don't know when all the callbacks are returned. But you know how many callbacks are there based on count of your origin manyFloats variable. All you need to do is keep a counter and add it up every time a callback is returned. And check if it equals the count of manyFloats then you can do the comparison:

int count = 0;
void myCallback(float f)
{
    ... usual stuff
    ... then
    if(count == manyFloats.Count) 
    {
        // do the comparison
    }
    else
    {
        count ++;
    } 
}
Comments