Simple understanding and application of C# multi-threaded eight-task Task II

Table of contents

1. Task

1.AsyncState   

2.CompletedTask     

3.CreationOptions     

4.CurrentId  

5.Exception   

6.Factory     

7.Id   

8.IsCanceled     

9.IsCompleted   

10.IsFaulted     

11.Status  

二.Task<TResult>

1.Result


Previous:

Simple understanding and application of C# multi-threaded seven-task Task

Following the previous article, we mainly talk about the attributes of Task in this article

Preface: The attribute descriptions of Task are basically copied from Task.Exception attribute (System.Threading.Tasks) | Microsoft Learn , just add your own understanding and test code and print for everyone's better understanding.

1. Task

1.AsyncState   

Gets the state object provided when creating the Task, or null if not provided.

Own test:

1.Task task=new Task(); task.Start(); in calling mode

Get the value of the state passed in by the following construction methods

        public Task(Action<object> action, object state);

        public Task(Action<object> action, object state, CancellationToken cancellationToken);
 
        public Task(Action<object> action, object state, TaskCreationOptions creationOptions);

        public Task(Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions);

Test code:

using(CancellationTokenSource source = new CancellationTokenSource()) {
            Task task = new Task((obj) => {
                Console.WriteLine("开始执行task任务:" + obj);
            }, (object)"xxx", source.Token, TaskCreationOptions.None);
            Console.WriteLine(task.AsyncState);
            task.Start();
        }

Print:

2.Task.Factory.StartNew(); in calling mode

Get the value of the state passed in by the following method

       public Task StartNew(Action<object> action, object state, CancellationToken cancellationToken);

        public Task StartNew(Action<object> action, object state, TaskCreationOptions creationOptions);

        public Task StartNew(Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler);

        public Task<TResult> StartNew<TResult>(Func<object, TResult> function, object state);

        public Task<TResult> StartNew<TResult>(Func<object, TResult> function, object state, CancellationToken cancellationToken);

        public Task<TResult> StartNew<TResult>(Func<object, TResult> function, object state, TaskCreationOptions creationOptions);

        public Task<TResult> StartNew<TResult>(Func<object, TResult> function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler);

        public Task StartNew(Action<object> action, object state);

Test code:

using(CancellationTokenSource source = new CancellationTokenSource()) {
            Task task1 = Task.Factory.StartNew((obj) => {
                Console.WriteLine("开始执行task1任务:" + obj);
            }, (object)"zzz", source.Token);
            Console.WriteLine(task1.AsyncState);
        }

Print:

2.CompletedTask     

Get a successfully completed task.
It took me a long time to understand this attribute. First of all, CompletedTask does not fetch your current completed Task . It will create an independent Task for you . In addition, using the CompletedTask and await async keywords is still single-threaded .

two examples

1. What CompletedTask fetches is not your currently completed Task

code:

using(CancellationTokenSource source = new CancellationTokenSource()) {
            for(int i = 0; i < 100; i++) {
                Task.Run(() => {
                    Console.WriteLine($"开始执行task{i}任务 taskID :{Task.CurrentId}");
                });
            }
            Thread.Sleep(1000);
            Console.WriteLine("获取一个完成任务ID:" + Task.CompletedTask.Id);
        }

Print:

 2.CompletedTask and await async keywords are still single-threaded

 code:

static async void  DoSomething() {
        Task task =  Task.Run(() => {
            Console.WriteLine("开始执行task");
        });
        await task;

        Console.WriteLine("DoSomething 获取当前执行线程" + Thread.CurrentThread.ManagedThreadId);
    }

    static async void DoSomething1() {
        await Task.CompletedTask;
        Console.WriteLine("DoSomething1 获取当前执行线程" + Thread.CurrentThread.ManagedThreadId);
    }
    static void Main(string[] args) {


        DoSomething();
        DoSomething1();
        Console.WriteLine("Main 获取当前执行线程" + Thread.CurrentThread.ManagedThreadId);
        Console.ReadLine();
}

Print:

3.CreationOptions     

Gets the TaskCreationOptions used to create this task.
Similar to AsyncState except that one is to get object state and the other is to get TaskCreationOptions

4.CurrentId  

Returns the ID of the currently executing Task.
Invoke an external call using Id in the current task execution

 code:

Task task1 = Task.Factory.StartNew((obj) => {
                Console.WriteLine("开始执行task1任务:" + obj + " ID :" + Task.CurrentId);
            }, (object)"zzz", source.Token);

5.Exception   

Obtains the prematurely terminated Task caused by AggregateException. This will return null if the Task completed successfully or has not raised any exceptions.

code:

using(CancellationTokenSource source = new CancellationTokenSource()) {
            Task task1 = new Task((obj) => {
                int[] num = new int[2];
                Task task = Task.Factory.StartNew(() => {
                    Console.WriteLine("开始执行task1子任务task:" + Task.CurrentId + num[3]);
                }, source.Token, TaskCreationOptions.AttachedToParent, TaskScheduler.Current);
                Console.WriteLine("开始执行task1任务:" + obj + " ID :" + Task.CurrentId);
            }, (object)"zzz", source.Token);
            task1.Start();
            Thread.Sleep(3000);
            Console.WriteLine(" 未经处理异常  : " + task1.Exception);
            Console.WriteLine(" 由于未经处理异常的原因  : " + task1.IsFaulted);
        }

Print:

6.Factory     

Provides access to factory methods for creating and configuring Task and Task<TResult> instances. 

7.Id   

Get the ID of this Task instance.
Use outside the Task

code:

Task task1 = Task.Factory.StartNew((obj) => {
                Console.WriteLine("开始执行task1任务:" + obj + " ID :" + Task.CurrentId);
            }, (object)"zzz", source.Token);

            Console.WriteLine("task1ID: " + task1.Id);

8.IsCanceled     

Gets whether this Task instance has finished executing due to the reason it was canceled.

code:

 using(CancellationTokenSource source = new CancellationTokenSource()) {
            Task task1 = Task.Factory.StartNew((obj) => {
                Console.WriteLine("开始执行task1任务:" + obj + " ID :" + Task.CurrentId);
            }, (object)"zzz", source.Token);
            source.Cancel();
            //Thread.Sleep(1000);
            Console.WriteLine(" 是否被取消结束的任务  : " + task1.IsCanceled);
        }

Print:

At this time, it is obviously cancelled, why is it printing false? Because the Task has not started to execute, it is detected
. Modification: 

using(CancellationTokenSource source = new CancellationTokenSource()) {
            Task task1 = Task.Factory.StartNew((obj) => {
                Console.WriteLine("开始执行task1任务:" + obj + " ID :" + Task.CurrentId);
            }, (object)"zzz", source.Token);
            source.Cancel();
            Thread.Sleep(1000);
            Console.WriteLine(" 是否被取消结束的任务  : " + task1.IsCanceled);
        }

Print:

9.IsCompleted   

  Gets a value indicating whether the task has been completed.

code:

using(CancellationTokenSource source = new CancellationTokenSource()) {
            Task task1 = Task.Factory.StartNew((obj) => {
                Console.WriteLine("开始执行task1任务:" + obj + " ID :" + Task.CurrentId);
            }, (object)"zzz", source.Token);
            source.Cancel();
            Thread.Sleep(1000);
            Console.WriteLine(" 是否被取消结束的任务  : " + task1.IsCanceled);
            Console.WriteLine(" 是否已经完成任务  : " + task1.IsCompleted);
        }

 Print:

It can be seen that even if the execution of the task is canceled, IsCompleted will return true to indicate that the task is completed

10.IsFaulted     

Gets whether the Task completed due to an unhandled exception.
Existing tests in Exception will not repeat them

11.Status  

   Get the TaskStatus of this task.

code:

        using(CancellationTokenSource source = new CancellationTokenSource()) {
            Task task1 = new Task((obj) => {
                Console.WriteLine("开始执行task1任务:" + obj + " ID :" + Task.CurrentId);
            }, (object)"zzz", source.Token);
            Console.WriteLine("task1任务状态1:" + task1.Status);
            task1.Start();
            Thread.Sleep(3000);
            Console.WriteLine("task1任务状态2:" + task1.Status);
        }

Print:

二.Task<TResult>

1.Result

Gets the result value of this Task<TResult>.
will block the thread

code:

Task<string> task = Task.Factory.StartNew<string>(() => {
            Thread.Sleep(1000);
            Console.WriteLine("开始执行task");
            return "返回值";
        });
        Console.WriteLine(task.Result);

        Console.WriteLine("执行主线程");
        Console.ReadLine();

 Print:

The attributes of the Task are finished here, and the next article will continue to write the methods of the Task.

If there is something wrong, I hope you can point it out, thank you very much.

In addition, the unfamiliar code must be written to deepen the memory, just read it and remember it for a long time.

Guess you like

Origin blog.csdn.net/SmillCool/article/details/127281963