A very basic explanation for threading in WPF?

前端 未结 3 1447
刺人心
刺人心 2021-01-06 11:49

I am very very new to WPF. I looked in the internet for several examples and tutorials about threading. They\'ve their own way to describe. But for naive like me, I want to

3条回答
  •  余生分开走
    2021-01-06 12:25

    Here is sample code snippet to handle WPF threading..

    Consider this scenario.

    we have to get some data from the server and after that we have play with data. means our next action is completely dependent on the callback or completion of Task.

    in this case we can use task factory ContinueWith method like following

    ObservableCollection images = new ObservableCollection();
    TaskFactory tFactory = new TaskFactory();
    tFactory.StartNew(() =>
    {
        for (int i = 0; i < 50; i++)
        {
        //GET IMAGE Path FROM SERVER
            System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)delegate()
            {
            // UPDATE PROGRESS BAR IN UI
            });    
        images.Add(("");
        }
    
    }).ContinueWith(t =>
    {
        if (t.IsFaulted)
        {
            // EXCEPTION IF THREAD IS FAULT
            throw t.Exception;
        }
        System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)delegate()
        {
            //PROCESS IMAGES AND DISPLAY
        });
    });
    

提交回复
热议问题