在线程中无法读取文件,请高手指点,谢谢!

xianglf 2006-09-27 02:21:07
using System;
using System.IO;
using System.Threading;

class ThreadTest
{
private static Thread mytd;
public static void Main()
{
mytd = new Thread(new ThreadStart(CreatFile));
mytd.Start();
}
public static void CreatFile()
{
string path = @"C:\Threadtestaa\threadaa.txt";
if(!File.Exists(path))
{
Directory.CreateDirectory(@"C:\Threadtestaa");
File.CreateText(path);
}
int icount = 50;
while(icount<=50)
{
StreamWriter sw = new StreamWriter(path);
sw.WriteLine("你好"+DateTime.Now);
sw.Close();
System.Threading.Thread.Sleep(300);
++icount;
}
mytd.Abort();
}
}

以上代码在运行的时候。出现IoException异常,异常说明为由另一个程序在使用C:\Threadtestaa\threadaa.txt这个文件。无法存取该文件。
想了很久不知道怎么回事。请高手指点一下。。非常感谢
...全文
112 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
whq1982 2006-09-27
  • 打赏
  • 举报
回复
File.CreateText(path);
这句打开了一个StreamWriter 应该关闭

StreamWriter sw = File.CreateText(path);
sw.close();
xiao_p 2006-09-27
  • 打赏
  • 举报
回复
代码没有看
按照说的错误应该是线程同步的问题
可以lock一下这个,在某个线程访问的时候
xiao_p 2006-09-27
  • 打赏
  • 举报
回复
上面的星星搞什么呢?
xianglf 2006-09-27
  • 打赏
  • 举报
回复
顶一下
xianglf 2006-09-27
  • 打赏
  • 举报
回复
哪位高人解释一下吧
viena 2006-09-27
  • 打赏
  • 举报
回复
@_@
Samen168 2006-09-27
  • 打赏
  • 举报
回复
up

111,119

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧