Oztaco
Oztaco

Reputation: 3459

Send a reference to a variable instead of it's value

I have a function that does a long task and I want to update a variable somewhere else occasionally with status updates. (If there is a better method for doing this, that's fine too) I'm writing a library and this code might be called several times at once so creating another variable in the same class that stores the variable isn't an option. Here is what my code might look like:

public static bool Count(int Progress, int CountToWhat) {
    for (int i = 0; i < CountToWhat; i++) {
        Progress = CountToWhat / i; // This is how I'd like to update the value, but obviously this is wrong
        Console.WriteLine(i.ToString());
    }
}

Upvotes: 3

Views: 140

Answers (4)

Eren Ers&#246;nmez
Eren Ers&#246;nmez

Reputation: 39095

A better way might be to pass an Action<int> delegate to be called to report progress:

public static bool Count(int CountToWhat, Action<int> reportProgress) 
{
    for (int i = 0; i < CountToWhat; i++) 
    {
        var progress = CountToWhat / i; 
        reportProgress(progress);
        Console.WriteLine(i.ToString());
    }
}

then you'd use it like:

Count(100, p => currentProgress = p);

You could also use the BackgroundWorker class to run your long running task, and utilize its ProgressChanged event.

Upvotes: 1

Aghilas Yakoub
Aghilas Yakoub

Reputation: 29000

You can use

int Progress = 0;
public static bool Count(ref int Progress, int CountToWhat)
{
  ....
}

Or

int Progress; //without init
public static bool Count(out int Progress, int CountToWhat)
{
  ....
}

Upvotes: 2

Marcel N.
Marcel N.

Reputation: 13986

This is not a good way of providing updates to your callers.

Better you define one ore more events in your class library (like OnError, OnProgress, etc.). You can raise, for example, OnProgress when you want to notify progress in a certain operation:

for (int i = 0; i < CountToWhat; i++) {
  OnProgress(CountToWhat / i);
  Console.WriteLine(i.ToString());
}

This is a much better way of doing it, especially when notifying from worker threads.

Upvotes: 4

itsme86
itsme86

Reputation: 19526

Change the signature to:

public static bool Count(ref int Progress, int CountToWhat)

And when you call it, use the ref keyword before the variable that you pass in as the first argument.

Upvotes: 3

Related Questions