Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
DotNETFrameworkNotesForProfessionals.pdf
Скачиваний:
32
Добавлен:
20.05.2023
Размер:
1.82 Mб
Скачать

Chapter 43: Task Parallel Library (TPL) API Overviews

Section 43.1: Perform work in response to a button click and update the UI

This example demonstrates how you can respond to a button click by performing some work on a worker thread and then update the user interface to indicate completion

void MyButton_OnClick(object sender, EventArgs args)

{

Task.Run(() => // Schedule work using the thread pool

{

System.Threading.Thread.Sleep(5000); // Sleep for 5 seconds to simulate work.

})

.ContinueWith(p => // this continuation contains the 'update' code to run on the UI thread

{

this.TextBlock_ResultText.Text = "The work completed at " + DateTime.Now.ToString()

},

TaskScheduler.FromCurrentSynchronizationContext()); // make sure the update is run on the UI thread.

}

GoalKicker.com – .NET Framework Notes for Professionals

137