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这个文件。无法存取该文件。
想了很久不知道怎么回事。请高手指点一下。。非常感谢
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这个文件。无法存取该文件。
想了很久不知道怎么回事。请高手指点一下。。非常感谢
解决方案 »
- 怎么将一个子窗体 以showdialog 方式显示呢
- C# RSA 自定义KEY 问题.
- 求思路,生成复杂PDF
- C#与C++编程语言选择问题
- 把一个Oracle blob字段里存储的tif格式图片取出后另存,修改后再存回数据库时发现图片变大,有没有解决办法啊?
- (有点难)高手请进(急急急急)!!!帮帮我!!!!
- 请教如何把WINFORM程序和.net framework一起打包成可安装文件。。谢谢。急。。
- 当方法中有out 或者ref参数时,应该怎么用MethodInfo.Invoke(...)调用
- 怎么获取一个网页的内容呢?
- 如何用c#实现ftp上传文件(100分相送)
- 请问如何设置滚动条的当前位置,就是用程序控制它向上或向下滚动,分不多,谢谢帮忙
- 怎样过滤FreeTextBox一类控件的不安全代码?
按照说的错误应该是线程同步的问题
可以lock一下这个,在某个线程访问的时候
这句打开了一个StreamWriter 应该关闭StreamWriter sw = File.CreateText(path);
sw.close();