为什么会结冰?

本文关键字:为什么 | 更新日期: 2023-09-27 18:08:50

这个程序在线程中写入从1到5000的数字,但是主形式冻结了。错误在哪里?提前感谢。

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        int how, current;
        bool job;
        Object lockobj = new Object();
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Started!");
            how = 5000;
            current = 0;
            job = true;
            Thread worker = new Thread(Go);
            worker.Name = "1";
            worker.Start();
        }
        private void Go()
        {
            while (job)
            {
                if (current < how)
                {
                    lock (lockobj)
                    {
                        current++;
                    }
                    log(string.Format("Thread #{0}: {1}", Thread.CurrentThread.Name, current));
                }
                else
                {
                    job = false;
                }
            }
        }

        private void log(string text)
        {
            Action A = new Action(() =>
            {
                richTextBox1.AppendText(text + System.Environment.NewLine);
            });
            if (richTextBox1.InvokeRequired)
                this.BeginInvoke(A);
            else A();
        }
    }

}

为什么会结冰?

因为你的大部分工作将花费在

        if (richTextBox1.InvokeRequired)
            this.BeginInvoke(A);

,当你调用表单时,它是锁定的。

做一些实际的工作,如Thread.Sleep(1000);:-),而不是current++;,您的表单将在更新之间响应

它会冻结,因为你在文本框上渲染得非常快,GUI没有时间保持同步。记住,这个渲染发生在主GUI线程上,通过调用BeginInvoke来如此快速地更新文本框实际上消耗了这个主GUI线程的所有资源。尝试降低记录的频率以避免这种行为。