I have WCF connector that should get some small amount of data for me, usually it takes up to 20 seconds to get this data for each item ( which is fine ). I want to use Task to get data for me and then add WinForm controls with value from this Tasks.
I've created list of objects which will consist this data.
Used first Task as the one which updates the list and i want Task that is right away after first Task is done to create controls.
This is the code so far:
List<IpVersionCounter> ipVersionCounters = new List<IpVersionCounter>(); Task task = Task.Factory.StartNew(() => { foreach (var sitein settings.Sites) { string ip = site.ip; string version = "undefined"; using (WcfConnector wcfConnector = WcfConnector.CreateConnectorWithoutException((ip))) { if (wcfConnector != null) { version= string.Format("{0} {1} {2}", wcfConnector.VersionController.GetBranchName(), wcfConnector.VersionController.GetBuildNumber(), wcfConnector.VersionController.GetCurrentVersion()); } } counter++; ipVersionCounters.Add(new IpVersionCounter { Ip = ip, Version = Version, Counter = counter }); } return ipVersionCounters; }).ContinueWith(); AddProgressBar(ipVersionCounter);
I don't know if i'm going right way and how to use ContinueWith to pass value from first method to second.
ContinueWith(Action<Task>)Creates a continuation that executes asynchronously when the target Task completes.
A continuation task (also known just as a continuation) is an asynchronous task that's invoked by another task, known as the antecedent, when the antecedent finishes.
c# - Run sequence of tasks, one after the other - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler.
In the example below previousTask
references the previous task, use the Result property to get the return value from it.
Task task = Task.Factory.StartNew(() => { // Background work return ipVersionCounters; }).ContinueWith((previousTask) => { var ipVersionCounters = previousTask.Result; });
Update
If you want the continuewith to execute on the UI thread use (If you are starting on the UI thread) ...
Task.Factory.StartNew(() => { // Background work }).ContinueWith((previousTask) => { // Update UI thread }, TaskScheduler.FromCurrentSynchronizationContext());
(which was taken from this answer for more info)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With