如何写个死循环,既不独占线程,又不阻塞UI线程?

Posted 秋荷雨翔的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何写个死循环,既不独占线程,又不阻塞UI线程?相关的知识,希望对你有一定的参考价值。

如果死循环独占线程,500个死循环要占用500个线程,如果死循环不独占线程,500个死循环,用200个线程也行,用20个线程也行,无非是执行的慢点

这样可以把同步操作改写为异步,并且节省线程占用

出个题:写个Socket服务端,接收数据不准用BeginReceive和ReceiveAsync,只能用Receive,Socket客户端10000个,线程池最大不准超过1000,如何实现?

代码:

技术图片
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Utils;

/**
 * 如何写个死循环,既不独占线程,又不阻塞UI线程
 * 
 * 
 * 
*/

namespace test
{
    public partial class Form1 : Form
    {
        private int _n = 0;
        private System.Windows.Forms.Timer _timer = null;
        private bool _run1 = false;
        private bool _run2 = false;

        public Form1()
        {
            InitializeComponent();
            _timer = new System.Windows.Forms.Timer();
            _timer.Interval = 10;
            _timer.Tick += (s, e) =>
            {
                if (_run1 || _run2)
                {
                    int a1; int a2; int m1; int m2;
                    ThreadPool.GetMaxThreads(out m1, out a1);
                    ThreadPool.GetAvailableThreads(out m2, out a2);
                    if ((m1 - m2) == 0)
                    {
                        Log("此刻辅助线程已全部释放");
                    }
                    if (_n % 10 == 0)
                    {
                        Log("当前使用辅助线程数:" + (m1 - m2) + ",当前使用异步线程数:" + (a1 - a2) + ",n=" + _n);
                    }
                }
            };
            _timer.Start();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 测试1
        /// </summary>
        private async void button1_Click(object sender, EventArgs e)
        {
            _n = 0;
            button1.Enabled = false;
            button2.Enabled = true;
            _run1 = true;
            _run2 = false;
            textBox1.Text = string.Empty;
            while (_run1) //此while不会独占线程
            {
                Task t = RunAsync(() =>
                {
                    Thread.Sleep(10);
                    Interlocked.Increment(ref _n);
                });
                await t;
            }
        }

        /// <summary>
        /// 测试2 
        /// </summary>
        private async void button2_Click(object sender, EventArgs e)
        {
            _n = 0;
            button1.Enabled = true;
            button2.Enabled = false;
            _run1 = false;
            _run2 = true;
            textBox1.Text = string.Empty;
            await Task.Factory.StartNew(() =>
            {
                while (_run2) //此while会独占一个线程
                {
                    Thread.Sleep(10);
                    Interlocked.Increment(ref _n);
                }
            });
        }

        #region 线程中执行
        /// <summary>
        /// 线程中执行
        /// </summary>
        public static async Task RunAsync(Action doWork, Action<Exception> errorAction = null)
        {
            await Task.Factory.StartNew(() =>
            {
                try
                {
                    doWork();
                }
                catch (Exception ex)
                {
                    if (errorAction != null) errorAction(ex);
                    LogUtil.Error(ex, "RunAsync错误");
                }
            });
        }
        #endregion

    }
}
View Code

 

以上是关于如何写个死循环,既不独占线程,又不阻塞UI线程?的主要内容,如果未能解决你的问题,请参考以下文章

HarmonyOS之深入解析线程间的通信

术语,概念

如何追踪阻塞主(UI)线程的调用?

Unity协程和线程的区别

Android Studio学习随笔-UI线程阻塞以及优化

如何在后台线程swift中运行for循环