. Net4.0 How to implement The. Task.run and Task.delay methods in NET4.5

Source: Internet
Author: User

Tag: height system execute test on () frame seconds oid Pos

Objective

. There are no Task.run and Task.delay methods under NET4.0, and. NET4.5 has been implemented for those who are still using. NET4.0, how do you implement both methods Under. NET4.0?

Under. NET4.0, There is a generic class called taskcompletionsource<treuslt>, which controls the behavior of a task, such as setting a result for a task, setting an exception, setting a cancellation, and so On.

MSDN is described in this way (url):

Represents the producer side of a task <tresult > that is not bound to a delegate , and provides access to the consumer side through the task Property.

It has the following two common methods:

1  public void SetException (Exception Exception);

You can use this method to set the exception for a task when there is an exception to the task that is being performed.

1  public void Setresult (TResult result);

This is to set a return value for the task, and if the task does not return a value, set null directly.

one, Task.run (action Action) method

The method implementation is similar to Task.Factory.StartNew (action action), and the implementation code is as Follows:

1          public StaticTask Run (action Action)2         {3             varTCS =Newtaskcompletionsource<Object>();4             NewThread (() = {5                 Try6                 {7 Action ();8Tcs. Setresult (NULL);9                 }Ten                 Catch(Exception Ex) one                 { a Tcs. SetException (ex); -                 } -}) {isbackground =true }. Start (); the             returnTcs. Task; -}

The purpose of this method is to execute the method represented by the delegate action and return the currently represented task, because the Method's signature return value type is task, so you need to set a null value for the Setresult method of the Tcs.

The test code is as Follows:

1             Taskex.run (() =2            {3                 thread.sleep (); 4                 Console.WriteLine ("Just for Test. " ); 5             });

The function of the code is to output the "Just for Test" string to the console after 5s.

Note: Taskex is a class used to encapsulate the run static method, the following is the Same.

second, task.run<tresult> (func<tresult> Function) method

The method is a generic version of Task.run (action action), implemented as Follows:

1          public StaticTask<tresult> run<tresult> (func<tresult>Function)2         {3             varTCS =NewTaskcompletionsource<tresult>();4             NewThread (() =5             {6                 Try7                 {8 Tcs. Setresult (function ());9                 }Ten                 Catch(Exception Ex) one                 { a Tcs. SetException (ex); -                 } -             }) the{isbackground =true }. Start (); -             returnTcs. Task; -}

Similar to the non-generic version of task.run, The method is intended to perform the method represented by the delegate function and to return the currently represented task, which is task<tresut>, with the return value of the Task.

The test code is as Follows:

1             string result = Taskex.run (() =2            {3                 thread.sleep (  ); 4                 return " Just for Test. " ; 5             }). Result; 6             Console.WriteLine (result);

The function of this method is the same as the example above: after 5s output the "Just for Test" string to the console, but it is implemented differently, one with the action delegate, and the other using the function<tresult> Delegate.

second, Task.delay (int MilliSeconds) method

1          public StaticTask Delay (intMilliseconds)2         {3             varTCS =Newtaskcompletionsource<Object>();4             varTimer =NewSystem.Timers.Timer (milliseconds) {AutoReset =false };5Timer. Elapsed + =Delegate{timer. Dispose (); Tcs. Setresult (NULL); };6 Timer. Start ();7             returnTcs. Task;8}

The above code feature uses the System.Timers.Timer class to implement the delay of the task, which is used to return the current task after milliseconds milliseconds, and the method does not block Anyone's threads.

The test code is as Follows:

1             Taskex.delay (the). Wait (); 2             Console.WriteLine ("Just for Test. ");

The function of this method is the same as the previous two, output the "Just for Test" string to the console after 5s.

Full code:

1 usingSystem;2 usingsystem.threading;3 usingSystem.Threading.Tasks;4 5 namespaceConsoleApp6 {7     class program8     {9         Static voidMain (string[] Args)Ten         { one             //task.run (action Action) method aTaskex.run (() = -             { -Thread.Sleep ( the); theConsole.WriteLine ("Just for Test."); -             }); -  -             //task.run<tresult> (func<tresult> Function) method +             stringresult = Taskex.run (() = -             { +Thread.Sleep ( the); a                 return "Just for Test."; at             }). Result; - Console.WriteLine (result); -  -             //task.delay (int MilliSeconds) method -Taskex.delay ( the). Wait (); -Console.WriteLine ("Just for Test."); in Console.readkey (); -         } to     } +     classTaskex -     { the          public StaticTask Run (action Action) *         { $             varTCS =Newtaskcompletionsource<Object>();Panax Notoginseng             NewThread (() = { -                 Try the                 { + Action (); aTcs. Setresult (NULL); the                 } +                 Catch(Exception Ex) -                 { $ Tcs. SetException (ex); $                 } -}) {isbackground =true }. Start (); -             returnTcs. Task; the         } -          public StaticTask<tresult> run<tresult> (func<tresult>Function)Wuyi         { the             varTCS =NewTaskcompletionsource<tresult>(); -             NewThread (() = wu             { -                 Try about                 { $ Tcs. Setresult (function ()); -                 } -                 Catch(Exception Ex) -                 { a Tcs. SetException (ex); +                 } the             }) -{isbackground =true }. Start (); $             returnTcs. Task; the         } the          public StaticTask Delay (intMilliseconds) the         { the             varTCS =Newtaskcompletionsource<Object>(); -             varTimer =NewSystem.Timers.Timer (milliseconds) {AutoReset =false }; inTimer. Elapsed + =Delegate{timer. Dispose (); Tcs. Setresult (NULL); }; the Timer. Start (); the             returnTcs. Task; about         } the     } the}

. Net4.0 How to implement The. Task.run and Task.delay methods in NET4.5

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.