繁体   English   中英

如何一次在ASP.net中执行方法

[英]How to execute a method one time in ASP.net

我有一个带有按钮的Web表单。当您单击该按钮时,它将创建一个文本文件并向其中写入内容。试想一下,例如我正在写1G内容的大文件,并且每天都会更改一次。这就是一个asp.net应用程序会被很多用户使用。因此,假设第一个用户在早上6点点击就会生成。现在我想重新使用它,直到第二天早上6点才创建一个新的。我正在发布一个小的原型代码

try
{
     File.WriteAllText("E:\\test.txt", "welcome");
}
catch (Exception ex)
{
      Response.Write(ex.Message);
}

注意:这是一个asp.net应用程序,所以无法想到thread.So,我不在考虑

While(true)
{
   Thread.Sleep()  etc
}

使用File.GetLastWriteTime方法检查文件中的最后修改

try
{
   if(!File.Exists("E:\\test.txt") )
   {
     File.WriteAllText("E:\\test.txt", "welcome");     
   } 
   else
   { 
       if(File.GetLastWriteTime(path).Day != DateTime.Now.Day)   
       {
         //code for next day
       }  
   }

}
catch (Exception ex)
{
  Response.Write(ex.Message);
}

假设您每天都在制作一个新文件,并且在一天结束时已经有删除逻辑。 创建文件之前,请检查文件是否存在。

try
        {
            if (//file does not exist)
               File.WriteAllText("E:\\test.txt", "welcome");
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

您还可以检查文件的日期,以及是否超出参数范围,然后删除并创建一个新文件(如果条件与“ exists”逻辑相同)。

这样可以防止两个或多个线程两次写入同一文件。

抓住锁的第一个线程将创建文件,然后其他线程将跳过创建文件,并在锁内对文件进行第二次检查。

public static object fileLock = new object();

public void createFile()
{

    if (File.Exists("filepath") == false) {

        lock (fileLock) {

            if (File.Exists("filepath") == false) {
                  File.WriteAllText("E:\\test.txt", "welcome");
            }

        }

    }
}

也许您应该尝试使用Application变量来存储上次写入文件的时间(日期值),并确保每天仅写入一次文件。 例如:

Dim dt as DateTime
If TryCast(Application("LastFileWrite"), dt) Then
    If String.Compare(dt.Date.ToString(), Now.Date.ToString()) <> 0 Then
        ' we're a different day today, go ahead and write file here
    End If
Else
    ' we've never writting this application variable, this is
    ' the first run, go ahead and write file here as well
End If

有关“应用程序”状态的更多信息,请查看以下文档:

https://msdn.microsoft.com/en-us/library/bf9xhdz4(v=vs.71).aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM