I’m calling a couple of functions during a form load and then using the result to update a label control. if the the functions are long running it stops the form from loading… so I want to make it that the form loads a works while the two functions are called in parallel and when they return it then updates the label here is the calling code both functions return an int.
This a windows Forms app in .Net 4.0
private void mainForm_Load(object sender, EventArgs e)
{
currentCount = func1(tes1);
allowedCount= func2(test2);
labelCount.Text = "Using " + func1.ToString() + " of " + func2.ToString();
}
updated 2001-08-27 to add continuous updates
I updated the code to also show how to use a .Forms GUI timer component to update a status bar label as background updates occur, also with some various cleanup and additional comments. It’s certainly also possible to do an Invoke() to update your form with information as it comes in, but I think it really doesn’t make much sense to do so. The goal of a UI update is to have adequate visual feedback given to the user, and there’s no need to couple the updating of the fields to the updating of the visual element.
Also if these updates come in frequently enough, you could end up with a big performance hit from all the calls to Invoke unless you rate-limit them, which is basically what is happening with the timer component anyway.
I have zipped up the solution and have made it available for download: ParallelButtons-7208779.zip. I’m not entirely certain why I chose that name, but there ya go. 🙂
So, the code now demonstrates how to do both: what I had originally interpreted the question to mean (to run two threads in parallel in the background, updating a label once both functions of returned), as well as adding in periodic updates of separate counter fields in the background threads that also have a status shown on the GUI, implemented by a
Timercomponent updating the labels in itsTickevent.For the final update based when the threads end, this setup doesn’t require any synchronization beyond what the structure already provides, at least from the perspective of updating things; I don’t know what your actual functions are doing. (If they interact with one another, they may have some synchronization requirements.) It also very quickly updates the form without even having to worry any sort of coordination or synchronization between the two threads in order to figure out which is responsbile for updating the GUI.
Form Code
Form Designer Code