26 Kasım 2020 Perşembe

Task Sınıfı Continuation

Giriş
Açıklaması şöyle
Before using the Task library, we had to use callback methods, but with TPL, it is much more comfortable. A simple way to chain threads and create a sequence of execution can be achieved by using Task.ContinueWith method. The ContinueWith method can be chained to the newly created Task or defined on a new Task object.

Another benefit of using the the the ContinueWith method is passing the previous task as a parameter, which enables fetching the result and processing it.
ContinueWith metodu - Action
Şöyle yaparız. ContinueWith metoduna geçilen parametre ana Task nesnesidir.
var t1 = new Task(() => ...);
var t2 = t1.ContinueWith((t) => ...);
t1.Start();
ContinueWith metodu - Action + TaskContinuationOptions
Açıklaması şöyle
The ContinueWith method accepts a parameter that facilitates the execution of the subsequent thread, TaskContinuationOptions, that some of its continuation options I find very useful:

- OnlyOnFaulted/NotOnFaulted (the continuing Task is executed if the previous thread has thrown an unhandled exception failed or not);
- OnlyOnCanceled/NotOnCanceled (the continuing Task is executed if the previous thread was canceled or not).

You can set more than one option by defining an OR bitwise operation on the TaskContinuationOptions items.
Örnek
Şöyle yaparız
// Initiate a library account object
LibraryAccount libraryAccount = new LibraryAccount(booksAllowance);
Task<int> task = Task.Factory.StartNew<int>(() =>{
  // The first task withdraws books
  libraryAccount.WithdrawBooks(booksToWithdraw);
  return libraryAccount.BorrowedBooksCount;
  })
  .ContinueWith<int>((prevTask) => {
    // Fetching the result from the previous task
    int booksInventory = prevTask.Result;
    Trace.WriteLine($"Current books inventory count {booksInventory}");
    // Return the books back to the library
    libraryAccount.ReturnBooks(booksToWithdraw);
    return libraryAccount.BorrowedBooksCount;
  }, // Set the conditions when to continue the subsequent task
  TaskContinuationOptions.NotOnFaulted | 
  TaskContinuationOptions.NotOnCanceled |
  TaskContinuationOptions.OnlyOnRanToCompletion);
  
// Wait for the task to end before continuing the main thread.
task.Wait();
// The actual number of books should remain the same
Assert.Equal(task.Result, booksAllowance);
ContinueWith metodu - Action + TaskScheduler
Örnek
Eğer task UI thread içinde başlatıldıysa arka plan iş bittikten sonra UI nesnesini güncellemek için şöyle yaparız.
public Action Worker = ...;
Task.Factory
    .StartNew(Worker)
    .ContinueWith(t => 
    { 
      ...
    }, TaskScheduler.FromCurrentSynchronizationContext()
);
Örnek
Şöyle yaparız

ContinueWhenAll metodu
Açıklaması şöyle
Besides calling the ContinueWith method, there are other options to run threads sequentially. The TaskFactory class contains other implementations to continue tasks, for example, ContinueWhenAll or ContinueWhenAny methods. The ContinueWhenAll method creates a continuation Task object that starts when a set of specified tasks has been completed. In contrast, the ContinueWhenAny method creates a new task that will begin upon completing any task in the set that was provided as a parameter.


Hiç yorum yok:

Yorum Gönder