C# Task, ContinueWith

Hello everybody,

today I want to write few words about Task Paralel library, and in particular two methods: Task.Start, and Task.ContinueWith.

Snippet

System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(
                () => {
                    //some heavy code like intensive calculations, reading from db, etc.
                    
                }
            );
 
            System.Threading.Tasks.Task t2 = t.ContinueWith(
                (a) => {
                //Code to update UI
                },
                TaskScheduler.FromCurrentSynchronizationContext()
            );

Following template has the following structure. You need to split your code in two parts. First one, is code which will be executed for non-Gui. Then the same task will work with GUI context and will be able to update GUI with results from Task t.

Another method which is worth menitioning is

Snippet

System.Threading.Tasks.Task.Factory.StartNew(
                () =>
                    {
                        //this code will be executed immediately
                    }
            );

Main difference is that code from factory will be executed immediately

No Comments

Add a Comment