net 多线程 学习 10 使用task启动线程

使用start和wait启动和等待线程完成

为什么要有Task。

Task => Thread + ThreadPool + 优化和功能扩展

Thread: 容易造成时间 + 空间开销,而且使用不当,容易造成线程过多,导致时间片切换。。。

ThreadPool: 控制能力比较弱。 做thread的延续,阻塞,取消,超时等等功能。。。。

            控制权在CLR,而不是在我们这里

Task 看起来像是一个Thread,Task 是在ThreadPool的基础上进行的封装。

.net 4.0之后,微软是极力的推荐 Task,来作为异步计算。

问题

Task是建立在ThreadPool上面吗???

我们的Task底层都是由不同的TaskScheduler支撑的。。。

TaskScheduler 相当于Task的CPU处理器。。。

默认的TaskScheduler是ThreadPoolTaskScheduler。。。

wpf中的TaskScheduler是 SynchronizationContextTaskScheduler

ThreadPoolTaskScheduler

this.m_taskScheduler.InternalQueueTask(this);


/*
 * a task example
 */
namespace TaskExample
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;

    public class Program
    {
        static void Main(string[] args)
        {
            // similar construction as Thread
            Task taskThatPrints = new Task(PrintHelloWorld);
            taskThatPrints.Start();

            // Task can return a value
            // you have to specify Task<T> when declaring so as to use Task.Result value to get the value back
            Task<string> taskThatReturnsValue = new Task<string>(ReturnsAvalue);
            taskThatReturnsValue.Start(); // start the thread
            taskThatReturnsValue.Wait(); // wait for this task to complete, if no wait, won't show the returned value
            Console.WriteLine(taskThatReturnsValue.Result); // once task completed, print out the value
        }

        private static string ReturnsAvalue()
        {
            Thread.Sleep(1000); // simulates some time spent 
            return "value";
        }

        private static void PrintHelloWorld()
        {
            Console.WriteLine("hello world!");
        }
    }
}


使用Task.Factory.StartNew创建新线程

// Task.Factory is another way to create a Task
Task<string> task = Task.Factory.StartNew<string>(
				() => GetPosts("https://jsonplaceholder.typicode.com/posts")
		);

SomethingElse();
task.Wait(); // I want to control this task to wait, if I don't want to control it, I can remove it
try
{
		// task.Result property will make the task to wait, if no Task.Wait() is called. 
		// but you still can use Task.Wait() if you want to control when and where to wait for the task.
		Console.WriteLine(task.Result);
}
// important to wrap this exception for task.Result, which is an AggregateException
catch(AggregateException ex)
{
		Console.WriteLine(ex.Message);
}

task 与 threadpool

task中的函数都会交给threadpool去执行,除非是longRunning才会独立开一个thread 而且task本身使用的是ThreadPool的线程,本身只有在task.Start()开始的时候 才开始用ThreadPool中的程序执行,并用task.Result返回结果


作者:spike

分类: Net

创作时间:2023-06-25

更新时间:2024-12-09

联系方式放在中括号之中例如[[email protected]],回复评论在开头加上标号例如:#1