C# Thread Task

1.Thread

            Thread thread = new Thread(()=>startBuffering(ratio, ratious, thickness));
            //thread.Priority = ThreadPriority.Lowest;
            thread.IsBackground = true;
            thread.Start();

2.Task


//1.通过start启动
var task1 = new Task(() =>
{
    //TODO you code
})
task1.start();
//2.直接运行
var task2 = Task.Factory.StartNew(() =>
{
    //TODO you code
});

//3.
task.Wait();
task.WaitAll();
Task.WaitAny();
Task.ContinueWith();  



//4.获取task结果
var SendFeedBackTask = Task.Factory.StartNew(() => { Console.WriteLine("Get some Data!"); }).ContinueWith<bool>(s => { return true; }).ContinueWith<string>(r => 
                              {
                                 if (r.Result)
                                 {
                                    return "Finished";
                                 }
                                 else
                                 {
                                    return "Error";
                                 }
                              });







//5.Task 的取消
//IsCancellationRequested
//https://johnthiriet.com/cancel-asynchronous-operation-in-csharp/


//6.返回值
//Task就是有返回值的Task,TResult就是返回值类型


Task<string> task = Task<string>.Run(() => {
    Thread.Sleep(2000); 
    return Thread.CurrentThread.ManagedThreadId.ToString(); 
});




你可能感兴趣的:(C#)