您的位置:首页 > 其它

多线程写文件异常(正由另一进程使用,因此该进程无法访问该文件)的解决方法

2010-04-29 15:06 886 查看
正由另一进程使用,因此该进程无法访问该文件。
在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
在 System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
在 System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)

这是由于多线程出现互斥,一个文件没关闭,继续写入数据流而产生的异常。

经过lock加锁没能解决问题,后来觉得用互斥量比较不错,经测试问题解决,异常通知没有了。

namespace filewrite
{
public partial class Form1 : Form
{
Mutex mtx = new Mutex();
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 30; i++)
{
Thread checkclientOnline = new Thread(checkOnline);
checkclientOnline.Start();
}

}
//写入日志
public static void WriteToLog1(string Title)
{

if (Title == "") return;
string FileName = Application.StartupPath;
//Object thisLock = new Object();

{
FileStream fs = new FileStream(FileName + "//tiplog.txt", FileMode.Append, FileAccess.Write, FileShare.Write);
Byte[] bTitle = UnicodeToMBCS(Title);
fs.Write(bTitle, 0, bTitle.Length);
fs.Close();
}
}

public static Byte[] UnicodeToMBCS(String src)
{
Encoding enc = Encoding.GetEncoding(936); ////Dont use codepage 52936, but 54936 or 936
int len = src.Length;

Byte[] tmpb = new Byte[len * 2];

tmpb = enc.GetBytes(src);

//string tmphead=tmpb.Length.ToString();
//tmphead=tmphead.PadLeft(4,'0');

//tmpb=enc.GetBytes(tmphead+src);
return tmpb;
}
void checkOnline()
{
while (true)
{
try
{

mtx.WaitOne();
//Write file here
WriteToLog1("hhh");
mtx.ReleaseMutex();
;
}catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐