Created
January 1, 2021 12:25
-
-
Save ierhalim/32d834243002e6d252dd2c4410a09eb5 to your computer and use it in GitHub Desktop.
Y6O3 Paralel Programlama
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Threading.Tasks; | |
| namespace TaskContinuationOptionsExample | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| var task1 = Task.Run(() => | |
| { | |
| Console.WriteLine("Task 1 running."); | |
| Random rnd = new Random(); | |
| if (rnd.Next(10) % 2 == 0) | |
| { | |
| throw new Exception("Something went wrong."); | |
| } | |
| return "Task 1 result"; | |
| }); | |
| // Bu task yalnızca task1 başarılı bir şekilde tamamlanırsa çalışacak. | |
| var successHandler = task1.ContinueWith((completedTask) => | |
| { | |
| Console.WriteLine("Task 1 completed, result is: {0}", completedTask.Result); | |
| }, TaskContinuationOptions.OnlyOnRanToCompletion); | |
| // Bu task yalnızca task1 hata verirse tamamlanacak. | |
| var failHandler = task1.ContinueWith((failedTask) => | |
| { | |
| Console.WriteLine("Task 1 failed. Status: {0}", task1.Status); | |
| }, TaskContinuationOptions.OnlyOnFaulted); | |
| try | |
| { | |
| // Bir task continuationOption parametresi yüzünden tamamlanmazsa Status propertysi Canceled olarak set edilir ve buda WaitHandler Task cancel edildiği için exception fırlatır. | |
| Task.WhenAll(new[] { successHandler, failHandler }).Wait(); | |
| } | |
| catch (AggregateException ex) | |
| { | |
| ex.Handle(e => true); | |
| } | |
| Console.WriteLine("task1 status: {0}", task1.Status); | |
| Console.WriteLine("successHandler status: {0}", successHandler.Status); | |
| Console.WriteLine("failHandle status: {0}", failHandler.Status); | |
| Console.ReadKey(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment