gpt4 book ai didi

c# - 当方法的新实例运行 C# 时,以前的方法仍在将数据写入文本文件

转载 作者:可可西里 更新时间:2023-11-01 11:21:25 25 4
gpt4 key购买 nike

我目前面临一个问题,我有一个方法可以查询服务器的特定端口并将结果写入名为 temp.txt 的文本文件。 Temp.txt 中不应该有任何重复数据 - 在方法开始之前文件应该是清晰的,尽管有时我发现该方法的前一个实例仍在运行(因为它是异步的)并且我经常得到重复数据,因为另一个方法仍在写入文件/执行查询。

代码片段:

            StreamWriter sw = File.AppendText("temp");
sw.WriteLine("Check1=Success");
sw.Close();

最佳答案

您可以实现某种 lock

Lock ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread attempts to enter a locked code, it will wait, block, until the object is released.

  class OnlyOneCallerAllowed
{
private static readonly object locker = new object();
public static void OnlyOneMethodCanWrite()
{
lock (locker)
{
using(StreamWriter sw = File.AppendText("temp"))
{
sw.WriteLine("Check1=Success");
}

}
}

关于c# - 当方法的新实例运行 C# 时,以前的方法仍在将数据写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8546274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com