risc-v中文社区

 找回密码
 立即注册
查看: 648|回复: 0

[原创] Task多线程

[复制链接]

347

主题

564

帖子

2237

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2237
发表于 2022-6-9 15:47:16 | 显示全部楼层 |阅读模式
    public partial class Test : Form
    {
        static StringBuilder sb = new StringBuilder();
        static int step = -1;
        public Test()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            step = -1;
            sb = new StringBuilder();
            string thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("①当前线程ID:{0}", thread_id));
            Task<int> t = Async3();//调用异步线程执行
            sb.AppendLine("④/⑤主线程结束.");//直接运行下去   本句和Async1中的“⑤/④当前线程ID。。。”有可能是本句在前打印,也有可能是async1中打印在前,主要是因为是并行执行
            timer1.Enabled = true;      
            //还有一个问题:本实验没有用到t值,比如取值用:t.Result,则会锁死在t.Result这句
        }
        public static int Async1()
        {
            string thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("⑤/④当前线程ID:{0}", thread_id)); //子线程中运行,也就是说Async1函数其实是和UI线程中button1_Click的sb.AppendLine(...)是并行执行的
            int sum = 0;
            for (int i = 0; i < 999; i++)
            {
                sum += i;
            }
            return sum;
        }

        public static async Task<int> Async2()
        {
            string thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("③当前线程ID:{0}", thread_id)); //也是UI线程
            int result = await Task.Run(new Func<int>(Async1));//await标记之后,代码在子线程中执行。
            thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("⑥当前线程ID:{0},result:{1}", thread_id, result)); //UI线程中执行
            return result;
        }

        public static async Task<int> Async3()
        {
            string thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("②当前线程ID:{0}", thread_id)); //UI线程
            int result = await Async2();
            thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("⑦当前线程ID:{0},result:{1}", thread_id, result));//UI线程中执行
            step = 1;
            return result;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (step > 0)
                timer1.Enabled = false;
            textBox1.Text = sb.ToString();
        }
    }

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则



Archiver|手机版|小黑屋|risc-v中文社区

GMT+8, 2024-4-30 22:31 , Processed in 0.015250 second(s), 17 queries .

risc-v中文社区论坛 官方网站

Copyright © 2018-2021, risc-v open source

快速回复 返回顶部 返回列表