C#使用线程锁来保证在多线程访问时同一个函数(文件)同一时间只有一个线程在操作
应用:多线程可以使UI界面和后台处理程序效率增加,但是有些函数(文件)在同一时刻只能有一个线程在操作,这个时候就要引入Lock的概念来保障。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp26
{
public partial class Form1 : Form
{
//新建一个Object类型的变量,用于标记线程占用
public static object obj = new object();
public Form1()
{
InitializeComponent();
}
public void show()
{
//MessageBox.Show("End");
}
public void test(TextBox textBox, Action ac)
{
//实例化Task
Task task = new Task(() =>
{
lock (obj)
{
for (int i = 0; i < 50; i++)
{
Thread.Sleep(100);
//Action 0-16个参数,没有返回值
Action action = new Action(() => { textBox.Text = $"当前计数为{i}"; });
//在拥有此控件的线程上执行指定的委托
Invoke(action);
}
//执行委托,即回调某一个函数,因为被执行的函数不需要返回值,所以使用Action
ac();
}
});
//启动Task
task.Start();
}
private void button1_Click(object sender, EventArgs e)
{
test(textBox1, new Action(show));
//Thread.Sleep(500);
test(textBox2, new Action(show));
}
}
}