[C#]『Task』任务并行库使用小计

1.简单创建使用

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
 
namespace ConsoleApplication17
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                /*
                 *  Task 类还提供了初始化任务但不计划执行任务的构造函数。 
                 *  出于性能方面的考虑,TaskFactory 的 StartNew 方法应该是创建和计划计算任务的首选机制,但是对于创建和计划必须分开的情况,
                 *  可以使用构造函数,然后可以使用任务的 Start 方法计划任务在稍后执行。
                 *  对于返回值的操作,应使用 Task<TResult> 类。————MSDN
                 */
                Task _task = new Task(() => { Console.WriteLine("my frist Task."); });
                _task.Start();
 
                Task _taskFactory = Task.Factory.StartNew(() => { Console.WriteLine("my frist Task by Factory."); });
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Exception Message:{0}", ex.Message.Trim()));
            }
            finally
            {
                Console.ReadLine();
            }
        }
 
    }
}

代码效果

[C#]『Task』任务并行库使用小计

 

2.Task处理返回值

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
 
namespace ConsoleApplication17
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Task<string> _task = Task<string>.Factory.StartNew(() =>
                {
                    string _guid = System.Guid.NewGuid().ToString();
                    Console.WriteLine(string.Format("Pass Value:{0}", _guid));
                    return _guid;
                });
                Console.WriteLine(string.Format("Task Return Value:{0}", _task.Result));
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Exception Message:{0}", ex.Message.Trim()));
            }
            finally
            {
                Console.ReadLine();
            }
        }
 
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

代码效果

[C#]『Task』任务并行库使用小计

 

3.Task 任务延续

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
 
namespace ConsoleApplication17
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                /*
                 * 使用 Task.ContinueWith 方法和 Task<TResult>.ContinueWith 方法,可以指定在前面的任务完成时要启动的任务。 
                 * 延续任务的委托中将传入对前面的任务的引用,以便它可以检查其状态。
                 * 此外,可以在 Result 属性中将用户定义的值从前面的任务传递到其延续任务,
                 * 以便前面的任务的输出可以作为延续任务的输入。————MSDN
                 */
                Task<string> _task = Task<string>.Factory.StartNew(() =>
                {
                    string _guid = "_task";
                    Console.WriteLine(_guid);
                    return _guid;
                }).ContinueWith<string>((guid) =>
                {
                    string _guid = "_task ContinueWith";
                    Console.WriteLine(string.Format("ContinueWith Task {0}", guid.Result));
                    return _guid;
                });
                Console.WriteLine(string.Format("Task Return Value:{0}", _task.Result));
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Exception Message:{0}", ex.Message.Trim()));
            }
            finally
            {
                Console.ReadLine();
            }
        }
 
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }代码效果

[C#]『Task』任务并行库使用小计

 

4.分离的嵌套任务

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication17
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                /*
                 * 如果在任务中运行的用户代码创建一个新任务,
                 * 且未指定 AttachedToParent 选项,则该新任务不采用任何特殊方式与外部任务同步。
                 * 此类任务称为“分离的嵌套任务”。 ————MSDN
                 * 说明:下面例子也来自于MSDN
                 * 其实意思就是父任务不会等待子任务
                 */
                Task _outer = Task.Factory.StartNew(() =>
                {
                    Console.WriteLine("Outer task beginning.");
                    Task _child = Task.Factory.StartNew(() =>
                    {
                        Thread.SpinWait(5000000);
                        Console.WriteLine("Detached task completed.");
                    });

                });
                 _outer.Wait();
                Console.WriteLine("Outer task completed.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Exception Message:{0}", ex.Message.Trim()));
            }
            finally
            {
                Console.ReadLine();
            }
        }

    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

代码效果

[C#]『Task』任务并行库使用小计

 

5.创建子任务

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication17
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                /*
                 * 如果在一个任务中运行的用户代码创建任务时指定了 AttachedToParent 选项,
                 * 则该新任务称为原始任务的子任务,原始任务称为父任务。
                 * 因为父任务隐式地等待所有子任务完成,所以可以使用 AttachedToParent 选项表示结构化的任务并行。 ————MSDN
                 * 说明:下面例子也来自于MSDN
                 * 其实意思就是父任务会等待子任务执行完后再结束
                 */
                Task _outer = Task.Factory.StartNew(() =>
                {
                    Console.WriteLine("Outer task beginning.");
                    Task _child = Task.Factory.StartNew(() =>
                    {
                        Thread.SpinWait(5000000);
                        Console.WriteLine("Detached task completed.");
                    }, TaskCreationOptions.AttachedToParent);

                });
                _outer.Wait();
                Console.WriteLine("Outer task completed.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Exception Message:{0}", ex.Message.Trim()));
            }
            finally
            {
                Console.ReadLine();
            }
        }

    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

代码效果

[C#]『Task』任务并行库使用小计

上一篇:arduino 蓝牙控制RGB LED灯


下一篇:BZOJ 2154: Crash的数字表格 [莫比乌斯反演]