I have a very contrived issue.
Imagine I have a class which has one method only and one field. Like:
public class WhereAmI
{
public int Number = 0;
public void Looping()
{
for (int i = 0; i < 100; i++)
{
Number = i;
Sleep(10000);
}
}
}
I call it from another class in the normal way you would expect
WhereAmI wai = new WhereAmI();
wai.Looping();
int CurrentNumber = wai.Number;
What I want is a way to see what number I’m currently up to and display that on screen. I’ve tried similar to the above but this won’t work because the compiler won’t move past the wai.Loopping() method until it’s complete.
I assume I have to do this on a new thread and then get into the world of cross threading? I then thought my design must be wrong and I’ve over complicating this!
Any one care to pass their opinion or suggestion on this?
Thank you
Assuming this code is running on the UI thread it could just update the UI directly within the loop. However if don’t want to mix UI code with your business logic (which is a good idea) then yes you will need to run this processing on another thread and have the UI thread either inspect this object, or preferably get event notifications as task progresses.
You should probably look at using BackgroundWorker to handle the processing. This class makes it simpler to farm out processing tasks like this and contains logic to support progress indicators.
The sample code in the MSDN article shows how you can set a lot of this up via drag and drop onto the design surface (assuming you’re using WinForms), and how to link the BackgroundWorker to a progress bar.