多线程写文件异常(正由另一进程使用,因此该进程无法访问该文件)的解决方法
正由另一进程使用,因此该进程无法访问该文件。
在 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加锁没能解决问题,后来觉得用互斥量比较不错,经测试问题解决,异常通知没有了。
view plaincopy to clipboardprint?
01.namespace filewrite
02.{
03. public partial class Form1 : Form
04. {
05. Mutex mtx = new Mutex();
06. public Form1()
07. {
08. InitializeComponent();
09. }
10.
11. private void button1_Click(object sender, EventArgs e)
12. {
13. for (int i = 0; i < 30; i++)
14. {
15. Thread checkclientOnline = new Thread(checkOnline);
16. checkclientOnline.Start();
17. }
18.
19. }
20. //写入日志
21. public static void WriteToLog1(string Title)
22. {
23.
24.
25. if (Title == "") return;
26. string FileName = Application.StartupPath;
27. //Object thisLock = new Object();
28.
29. {
30. FileStream fs = new FileStream(FileName + "http://www.cnblogs.com/itecho/admin/file://tiplog.txt/", FileMode.Append, FileAccess.Write, FileShare.Write);
31. Byte[] bTitle = UnicodeToMBCS(Title);
32. fs.Write(bTitle, 0, bTitle.Length);
33. fs.Close();
34. }
35. }
36.
37. public static Byte[] UnicodeToMBCS(String src)
38. {
39. Encoding enc = Encoding.GetEncoding(936); ////Dont use codepage 52936, but 54936 or 936
40. int len = src.Length;
41.
42. Byte[] tmpb = new Byte[len * 2];
43.
44. tmpb = enc.GetBytes(src);
45.
46. //string tmphead=tmpb.Length.ToString();
47. //tmphead=tmphead.PadLeft(4,'0');
48.
49. //tmpb=enc.GetBytes(tmphead+src);
50. return tmpb;
51. }
52. void checkOnline()
53. {
54. while (true)
55. {
56. try
57. {
58.
59. mtx.WaitOne();
60. //Write file here
61. WriteToLog1("hhh");
62. mtx.ReleaseMutex();
63. ;
64. }catch(Exception e)
65. {
66. Console.WriteLine(e.ToString());
67. }
68. }
69. }
70. }
71.}