如果死循环独占线程,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
}
}
来源:oschina
链接:https://my.oschina.net/u/4344191/blog/4315150