Tasks in C#

بما ان unity اصبح يدعم c# version 6,7 فاصبح من اللازم التحدث عن الكلاسس System.Threading.Tasks.Task وهو ماسوف يفيدنا في عمل ال multithreads بدلا من استخدام الكلاسس Thread و ThreadPool
في الحقيقة من السهل العمل على ThreadPool  اكثر من Task ولكن يعيبه انه ليس بامكانك التاكد من حالة الthread هل تم الانتهاء منه وماهي نتيجته لهذا قامت c# بتقديم الكلاسس Task وهي مهمة يجب ان يقوم بها ويعيد نتيجة بامكانك الوصول لها بعد التاكد من ان الحسابات قد انتهت  .

 

Properties of Task Class:

Property Description
Exception Returns any exceptions that caused the task to end early
Status Returns the Tasks status
IsCancelled Returns true if the Task was cancelled
IsCompleted Returns true if the task is completed successfully
IsFaulted Returns true if the task is stopped due to unhandled exception
Factory Provides acess to TaskFactory class. You can use that to create Tasks
Result get the returned value from task

Methods of Task Class:

Methods Purpose
ConfigureAwait You can use Await keyword for the Task to complete
ContinueWith Creates continuation tasks.
Delay Creates a task after specified amount of time
Run Creates a Task and queues it to start running
RunSynchronously Runs a task Synchronously
Start Starts a task
Wait Waits for the task to complete
WaitAll Waits until all tasks are completed
WaitAny Waits until any one of the tasks in a set completes
WhenAll Creates a Task that completes when all specified tasks are completed
WhenAny Creates a Task that completes when any specified tasks completes

مثال بسيط

Task<int> t = Task.Run(() =>
{
    return 100;
});
t.Wait();
print(t.Result); // Displays 100

مثال لل parent task

void SimpleNestedParentTask()
{
    var parent = Task.Factory.StartNew(() =>
    {
         print(1);
         var child = Task.Factory.StartNew(() =>
         {
             print(2);
             Thread.Sleep(3000);
             print(3);
         },TaskCreationOptions.AttachedToParent);
     });

     parent.Wait();
     print(4);
}

وهي تكافئ ل nasted task التالي

void SimpleNestedTask()
    {
        var parent = Task.Run(() =>
        {
            print(1);
            var child = new Task(()=>
            {
                print(2);
                Thread.Sleep(3000);
                print(3);
            });
            child.Start();
            child.Wait();
        });

        parent.Wait();
        print(4);
}
void NastedTask()
{
   Task <Int32[]> parent =  Task.Factory.StartNew(() =>
   {
       var results = new Int32[100];
       for (int i = 0; i < 100; i++)
       {
           int ii = i;
           new Task(() => { results[ii] = ii*10; }, TaskCreationOptions.AttachedToParent).Start();
       }
       return results;
   })
   var finalTask = parent.ContinueWith(//Creates a continuation that executes asynchronously when the target Task<TResult> completes and returns a value.
   parentTask => {
       print(Thread.CurrentThread.Name);
       foreach (int i in parentTask.Result)
           print(i);
   });
   finalTask.Wait();
}

finaltask يتم تنفيذه بعد الانتهاء من parent و parent ينتهي عندما يتم الانتهاء من تنفيذ كل الابناء .

مثال task factory

Task <Int32[]> parent =  Task.Factory.StartNew(() =>
{
    var results = new Int32[100];
    TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent,
        TaskContinuationOptions.ExecuteSynchronously);
                
    for (int i = 0; i < 100; i++)
    {
        int ii = i;
        tf.StartNew(() => { results[ii] = ii*10; });
    }
    return results;
 });
 var finalTask = parent.ContinueWith(
 parentTask => {
     foreach (int i in parentTask.Result)
         print(i);
     });
finalTask.Wait();

 

الكلمات المفتاحية async  و await

هو طريقة لعمل تززامن في اداء ال tasks
اي method يستخدم async اما ان يعيد task او void

async void doMession()
{
      Task<int> t=Task.Run(()=>{
         Thread.Sleep(10000);
         return 100;
     });
     int res=await t;// wait 10 seconds then res=100
     print(res);//100
}