ComplianceServer/oldcode/ConsoleApp2/Program.cs

80 lines
3.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("我是主线程线程ID" + Thread.CurrentThread.ManagedThreadId);
////task用法一
//Task task1 = new Task(() => MyAction());//异步调用任务
//task1.Start();
//Console.WriteLine("***");
////task用法二
//var strRes = Task.Run<string>(() => { return GetReturnStr(); });//同步等待返回值
//Console.WriteLine(strRes.Result);
//task->async异步方法和await主线程碰到await时会立即返回继续以非阻塞形式执行主线程下面的逻辑
Console.WriteLine("---------------------------------");
Console.WriteLine("①我是主线程线程ID{0}", Thread.CurrentThread.ManagedThreadId);
var testResult = TestAsync();
Console.WriteLine("@@@@@@@@@@");
//Console.WriteLine("Main_1:{0}", Thread.CurrentThread.ManagedThreadId);
//A();
//Console.WriteLine("Main_2{0}", Thread.CurrentThread.ManagedThreadId);
Console.ReadKey();
}
static async Task A()
{
Console.WriteLine("1线程ID{0}", Thread.CurrentThread.ManagedThreadId);
B();
Console.WriteLine("1线程ID{0}", Thread.CurrentThread.ManagedThreadId);
}
static async Task B()
{
Thread.Sleep(1000);
Console.WriteLine("2线程ID{0}", Thread.CurrentThread.ManagedThreadId);
}
static async Task TestAsync()
{
Console.WriteLine("②调用GetReturnResult()之前线程ID{0}。当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
var name = GetReturnResult();
Console.WriteLine("④调用GetReturnResult()之后线程ID{0}。当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
Console.WriteLine("⑥得到GetReturnResult()方法的结果一:{0}。当前时间:{1}", await name, DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
Console.WriteLine("⑥得到GetReturnResult()方法的结果二:{0}。当前时间:{1}", name.GetAwaiter().GetResult(), DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
}
static async Task<string> GetReturnResult()
{
Thread.Sleep(2000);
Console.WriteLine("③执行Task.Run之前, 线程ID{0}", Thread.CurrentThread.ManagedThreadId);
return await Task.Run(() =>
{
Thread.Sleep(2000);
Console.WriteLine("⑤GetReturnResult()方法里面线程ID: {0}", Thread.CurrentThread.ManagedThreadId);
return "我是返回值";
});
}
static void MyAction()
{
Console.WriteLine("1我是新进程线程ID" + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(2000);
Console.WriteLine("2我是新进程线程ID" + Thread.CurrentThread.ManagedThreadId);
}
static string GetReturnStr()
{
Thread.Sleep(2000);
return "我是返回值线程ID" + Thread.CurrentThread.ManagedThreadId;
}
}
}