当前位置: 代码网 > it编程>编程语言>Asp.net > C#中Task任务类用法详解

C#中Task任务类用法详解

2024年11月13日 Asp.net 我要评论
前言task类是.net平台上进行多线程和异步操作的重要工具。它提供了简洁而强大的api支持,使得开发者能够更加高效地利用系统资源,实现复杂的并行和异步操作。无论是在i/o密集型操作还是cpu密集型任

前言

task类是.net平台上进行多线程和异步操作的重要工具。它提供了简洁而强大的api支持,使得开发者能够更加高效地利用系统资源,实现复杂的并行和异步操作。无论是在i/o密集型操作还是cpu密集型任务中,task类都能为开发者提供有力的支持。

认识task

命名空间:system.threading.tasks

类名:task

task顾名思义就是任务的意思

task是在线程池基础上进行的改进,它拥有线程池的优点,同时解决了使用线程池不易控制的弊端。

它是基于线程池的优点对线程的封装,可以让我们更方便高效的进行多线程开发。

简单理解:

task的本质是对线程thread的封装,它的创建遵循线程池的优点,并且可以更方便的让我们控制线程。

一个task对象就是一个线程。

创建无返回值task的三种方式

第一种方式

通过new一个task对象传入委托函数并启动

        task t1 = new task(() =>
        {
            int i = 0;
            while (isruning)
            {
                print("方式一:" + i);
                ++i;
                thread.sleep(1000);
            }
        });
        t1.start();

第二种方式

通过task中的run静态方法传入委托函数

        task t2 = task.run(() =>
        {
            int i = 0;
            while (isruning)
            {
                print("方式二:" + i);
                ++i;
                thread.sleep(1000);
            }
        });

第三种方式

通过task.factory中的startnew静态方法传入委托函数

task t3 = task.factory.startnew(() =>
{
    int i = 0;
    while (isruning)
    {
        print("方式三:" + i);
        ++i;
        thread.sleep(1000);
    }
});

返回有返回值的task

第一种方式

通过new一个task对象闯入委托函数并启动

t1 = new task<int>(() =>
{
    int i = 0;
    while (isruning)
    {
        print("方式一:" + i);
        ++i;
        thread.sleep(1000);
    }
    return 1;
});
t1.start();

第二种方式

通过task中的run静态方法传入委托函数

t2 = task.run<string>(() =>
{
    int i = 0;
    while (isruning)
    {
        print("方式二:" + i);
        ++i;
        thread.sleep(1000);
    }
    return "1231";
});

第三种方式

通过task.factory中的startnew静态方法传入委托函数

t3 = task.factory.startnew<float>(() =>
{
    int i = 0;
    while (isruning)
    {
        print("方式三:" + i);
        ++i;
        thread.sleep(1000);
    }
    return 4.5f;
});

获取返回值

注意:

resut获取结果时会阻塞线程

即如果task没有执行完成

会等待task执行完成获取到result

然后再执行后边的代码,也就是说 执行到这句代码时 由于我们的task中是死循环 

所以主线程就会被卡死

同步执行task

之前我们举的例子都是通过多线程异步执行的

如果希望task能够同步执行

只需要调用task对象中的runsynchronously方法

注意:需要使用 new task对象的方式,因为run和startnew在创建时就会启动

        task t = new task(() =>
        {
            thread.sleep(1000);
            print("这是一段话");
        });
        //t.start();
        t.runsynchronously();
        print("主线程执行");

不start 而是 runsynchronously

task中线程阻塞的方式

1.wait方法:等待任务执行完毕,再执行后面的内容

 task t1 = task.run(() =>
 {
     for (int i = 0; i < 5; i++)
     {
         print("t1:" + i);
     }
 });

 task t2 = task.run(() =>
 {
     for (int i = 0; i < 20; i++)
     {
         print("t2:" + i);
     }
 });
​​​​​​​//t2.wait();

2.waitany静态方法:传入任务中任意一个任务结束就继续执行

task.waitany(t1, t2);

3.waitall静态方法:任务列表中所有任务执行结束就继续执行

task.waitall(t1, t2);

task完成后继续其它task(任务延续)

 1.whenall静态方法 + continuewith方法:传入任务完毕后再执行某任务

using system.threading;
using system.threading.tasks;
using unityengine;
 
public class test : monobehaviour
{
    task t1,t2;
 
    bool isruning =true;
    void start()
    {
        task.whenall(t1, t2).continuewith((t) =>
        {
            print("一个新的任务开始了");
            int i = 0;
            while (isruning)
            {
                print(i);
                ++i;
                thread.sleep(1000);
            }
        });
 
        task.factory.continuewhenall(new task[] { t1, t2 }, (t) =>
        {
            print("一个新的任务开始了");
            int i = 0;
            while (isruning)
            {
                print(i);
                ++i;
                thread.sleep(1000);
            }
        });
 
    }
    private void ondestroy()
    {
        isruning = false;
    }
}

2.whenany静态方法 + continuewith方法:传入任务只要有一个执行完毕后再执行某任务 

using system.threading;
using system.threading.tasks;
using unityengine;
 
public class test : monobehaviour
{
    task t1,t2;
 
    bool isruning =true;
    void start()
    {
        task.whenany(t1, t2).continuewith((t) =>
        {
            print("一个新的任务开始了");
            int i = 0;
            while (isruning)
            {
                print(i);
                ++i;
                thread.sleep(1000);
            }
        });
 
        task.factory.continuewhenany(new task[] { t1, t2 }, (t) =>
        {
            print("一个新的任务开始了");
            int i = 0;
            while (isruning)
            {
                print(i);
                ++i;
                thread.sleep(1000);
            }
        });
 
    }
    private void ondestroy()
    {
        isruning = false;
    }
}

取消task执行

方法一:通过加入bool标识 控制线程内死循环的结束

方法二:通过cancellationtokensource取消标识源类 来控制

cancellationtokensource对象可以达到延迟取消、取消回调等功能

using system.threading;
using system.threading.tasks;
using unityengine;
 
public class test : monobehaviour
{
    task t1,t2;
 
    cancellationtokensource c;
    void start()
    {
        c = new cancellationtokensource();
        //延迟取消
        c.cancelafter(5000);
        //取消回调
        c.token.register(() =>
        {
            print("任务取消了");
        });
        task.run(() =>
        {
            int i = 0;
            while (!c.iscancellationrequested)
            {
                print("计时:" + i);
                ++i;
                thread.sleep(1000);
            }
        });
 
    }
    private void ondestroy()
    {
        c.cancel();
    }
}

总结

1.task类是基于thread的封装

2.task类可以有返回值,thread没有返回值

3.task类可以执行后续操作,thread没有这个功能

4.task可以更加方便的取消任务,thread相对更加单一

5.task具备threadpool线程池的优点,更节约性能

到此这篇关于c#中task任务类用法详解的文章就介绍到这了,更多相关c# task任务类内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com