110,535
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
namespace testThreadLock
{
public partial class Form1 : Form
{
int threadNum = 10;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 1; i <= threadNum; i++)
{
Thread t = new Thread(new ThreadStart(run));
t.Name = i.ToString();
t.Start();
}
}
private void run()
{
string filePath = @"D:\PHOTO\info.txt";
StreamWriter sw = File.CreateText(filePath);
sw.WriteLine("test");
sw.Close();
}
}
}
string filePath = @"D:\PHOTO\info.txt";
StreamWriter sw = File.CreateText(filePath);
sw.WriteLine("test");
sw.Close();
加了锁,如果我在这个run方法里还有其他的操作,会不会有影响呢?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
namespace CSharpWin02
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int threadNum = 10;
for (int i = 1; i <= threadNum; i++)
{
Thread t = new Thread(new ThreadStart(run));
t.Name = i.ToString();
t.IsBackground = true;//如果到界面退出还没执行完成,则随界面一起退出。
t.Start();
}
}
//创建文件,当前文件目录下创建info.txt
StreamWriter sw = File.CreateText(@"info.txt");
private void run()
{
lock (sw)
{
sw.WriteLine(Thread.CurrentThread.Name);
sw.Flush();//写入文件
}
}
}
}
StreamWriter sw = File.CreateText(@"D:\PHOTO\info.txt");
,报错“文件“D:\PHOTO\info.txt”正由另一进程使用,因此该进程无法访问该文件。”
StreamWriter sw = File.CreateText(@"D:\PHOTO\info.txt");
private void run()
{
lock(sw)
{
sw.Open();
sw.WriteLine("test");
sw.Close();
}
}