I'm working on a WinForm app (using .NET 4.0) which has several tabs filled with data regarding Shipments. Currently, when a user clicks on a tab a specific method is called, in which each control of the selected tab is populated with the relevant data.
We are working with an outside consultant who mentioned that our application could benefit from the TPL, so I started to research the TPL. I'm still very much in the process of researching as well as trying out small samples and tutorials I find online, but I believe I'm ready to implement the TPL in our existing code.
So what I would like to do in my first attempt is to go ahead and call each of the selected tab load methods on the initial load of a Shipment, rather than waiting for the user to click on the tab.
In the calling method, I have the following code (I didn't include every TaskFactory call as it would be a waste of space in this example.)
Tasks.Task.Factory.StartNew(Function() LoadSummaryTab())
Tasks.Task.Factory.StartNew(Function() LoadRouteTab())
I tried running the code, but ran into cross-thread issues. After researching that issue, I found that it is due to ui controls being updated in each of the two methods I've called.
So I found some samples online that suggest I use SyncronizationContext, but I'm beginning to wonder if what I'm trying to do is even worth it.
Using what I researched online, I created a simple WinForm application to test out the code I found. Is this anywhere near the correct solution for what I'm trying to do? This succesfully resolves my cross-thread issue, but obviously this is not like my real-world situation.
private void Form1_Load(object sender, EventArgs e)
{
var ui = TaskScheduler.FromCurrentSynchronizationContext();
var tf = Task.Factory;
var task = tf.StartNew(() =>
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(10);
};
});
task.ContinueWith(x =>
{
label1.Text = "I am label 1.";
label2.Text = "I am label 2.";
label3.Text = "I am label 3.";
label4.Text = "I am label 4.";
}, ui);
}
I found an answer here - Use Begin Invoke, but it seems that I will have a bit of repetitive code since I have so many controls to update. Is BeginInvoke the best idea for what I'm trying to do?
I'm just looking to get feedback from other experienced developers who have been down this road and can advise me. I do need to stay on the path which the consultant has advised us to go on, so TPL needs to be the primary focus.
So I'll end with this question. Considering the limited information I've provided, does it makes sense for me to try and execute all the loadselectedtab methods using TPL, especially considering that several UI controls are updated in each method? If so, would anyone be able to advise me in pursuing this path?