C#-多线程-任务-启动
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp16
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
mian();
//main2();
//main3();
Thread.Sleep(500);
}
static void mian() {
var tf = new TaskFactory();
Task t1 = tf.StartNew(fun, "t1");
Task t2 = Task.Factory.StartNew(fun, "t2");
Task t3 = new Task(fun, "t3");
t3.Start();
Task t4 = Task.Run(() => fun("t4"));
}
// 同步任务-运行在一个线程
static void main2() {
fun("mian2");
var t1 = new Task(fun, "main2 t1");
t1.RunSynchronously();
}
// 使用单独线程的任务
static void main3() {
var t1 = new Task(fun, "main3 t1",TaskCreationOptions.LongRunning);
t1.Start();
}
static void fun(Object o) {
Console.WriteLine(o.ToString());
log();
}
static void log() {
Console.WriteLine("线程状态观察");
Console.WriteLine($"Task id:{Task.CurrentId?.ToString()??"no task"}," + $"thread:{Thread.CurrentThread.ManagedThreadId}");
Console.WriteLine($"Thread.CurrentThread.IsThreadPoolThread:"+$"{Thread.CurrentThread.IsThreadPoolThread}");
Console.WriteLine($"Thread.CurrentThread.IsBackground:"+$"{Thread.CurrentThread.IsBackground}");
Console.WriteLine();
}
}
}
启动方式
同步任务-运行在一个线程
使用单独线程的任务