代码搬运笔记
1. 多线程加速计算
public
static
int
count = 0;
public
static
object
o =
new
object
();
private
static
void
Calculation()
{
lock
(o)
//加锁
{
for
(
int
j = 0; j < 10000000; j++)
{
count = count + 1;
}
}
}
调用:
List<IAsyncResult> listAction =
new
List<IAsyncResult>();
for
(
int
i = 0; i < 20; i++)
{
//创建线程 总共20个线程
listAction.Add(
new
Action(() =>
{
Calculation();
}).BeginInvoke(
null
,
null
));
}
//等所有线程都结束
while
(listAction.Count(r => !r.IsCompleted) > 0)
{
Thread.Sleep(100);
}
Console.WriteLine(
"加锁---计算结果为:{0}"
, count);
2. 关于四舍五入
Math.Round(4.5)
//结果为4
Math.Round(4.5, MidpointRounding.AwayFromZero)
//这样的结果才是 5
Math.Round(4.555, 2, MidpointRounding.AwayFromZero)
// 保留2位小数据 这样的结果才是 4.56
3.DataGridView只清空数据不清空表头
DataTable dt = (DataTable)dataGridView1.DataSource;
if
(dt !=
null
)
{
dt.Rows.Clear();
}
dataGridView1.DataSource = dt;
4.时间格式转换
string
str=
"20181008232349"
;
//用 DateTime dt=Convert.ToDateTime(str); 这样转会转换失败
//方法一
DateTime dt = DateTime.ParseExact(str,
"yyyyMMddHHmmss"
, System.Globalization.CultureInfo.CurrentCulture);
//方法二
DateTime result;
DateTime.TryParseExact(str,
"yyyyMMddHHmmss"
, System.Globalization.CultureInfo.CurrentCulture,System.Globalization.DateTimeStyles.AllowWhiteSpaces,
out
result);