码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-06-17 20:37:40      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:spl   接收   one   bsp   button   col   img   als   占用   

如果死循环独占线程,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线程?

标签:spl   接收   one   bsp   button   col   img   als   占用   

原文地址:https://www.cnblogs.com/s0611163/p/13154263.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!