【发布时间】:2017-12-05 03:01:00
【问题描述】:
我是编程新手,我有一个问题。如果我有两个函数,一个创建一个文本文件并写入其中,而另一个打开同一个文本文件并从中读取。
我得到的错误是:
System.IO.IOException: '进程无法访问文件'@.txt' 因为它正被另一个进程使用。'
我已经尝试为每个功能设置单独的计时器,但它仍然不起作用。我认为最好的方法是功能二直到功能一结束才开始。
你能帮我实现吗? 非常感谢! 迈克
源代码:
public Form1() {
InitializeComponent();
System.Timers.Timer timerButtona1 = new System.Timers.Timer();
timerButtona1.Elapsed += new ElapsedEventHandler(tickTimera1);
timerButtona1.Interval = 3003;
timerButtona1.Enabled = true;
}
private async void tickTimera1(object source, ElapsedEventArgs e) {
function1();
function2();
}
void function1() {
List<string> linki = new List<string>();
linki.Add("https://link1.net/");
linki.Add("https://link2.net/");
linki.Add("https://link3.net/");
List<string> fileNames = new List<string>();
fileNames.Add("name1");
fileNames.Add("name2");
fileNames.Add("name3");
for (int x = 0; x < fileNames.Count; x++) {
GET(linki[x], fileNames[x]);
//System.Threading.Thread.Sleep(6000);
}
}
async void GET(string link, string fileName) {
var ODGOVOR = await PRENOS_PODATKOV.GetStringAsync(link);
File.WriteAllText(@"C:\Users\...\" + fileName + ".txt", ODGOVOR);
}
void function2() {
string originalText = File.ReadAllText(@"C:\Users\...\fileName.txt", Encoding.Default);
dynamic modifiedText = JsonConvert.DeserializeObject(originalText);
//then i then i read from the same text files and use some data from it..
}
【问题讨论】:
-
显示你的源代码。
-
释放所有对象.....
-
可能是您在完成写入文件后并没有关闭文件。
-
代码很长很乱。基本上一个函数将数据保存到文本文件,然后另一个函数进入并从文件中读取。整个过程一次又一次地重复。我的代码是初学者而且非常混乱。
-
贴出函数的代码和出错的地方..
标签: c# concurrency ioexception