任务和计时器 c# 上出错



先生,女士我有问题。出现错误:"进程无法访问文件'C:\temps\1.pdf',因为它正被另一个进程使用。 我想做的是访问该路径而不会出错。

我有一个名为"temps"的文件夹,这是我存储pdf的地方。

我的计时器设置为 10 毫秒。每 10 毫秒,我的命令"SELECT * FROM schedule WHERE CustID=@ID && St=@stnow && Se=@sen"将执行一次,之后我的 DataAdapter "ad" 将填充我的数据集"ds"供我的 ReportClass "report2" 使用,将 pdf 导出到我的文件夹 "temps"。

如果我的代码或我构建代码的方式有问题,请启发我" 注意:"这个项目是为了提高我的技能。我接受建设性的批评,非常感谢您的回复/回复。

下面是我的代码:

private void Elapsed_Time_Tick(object sender, EventArgs e)
{
  label1.Text = DateTime.Now.ToLongTimeString();
  DateTime timeticking = DateTime.Now; // Just to check my time.
  Task t = new Task(() => getreport()); // run my function
  t.Start();
}
private void getreport()
{
  using (MySqlConnection con4 = new MySqlConnection(connString))
  {
   con4.Open();
   using (MySqlCommand com4 = new MySqlCommand("SELECT * FROM 
          schedule WHERE CustID=@ID && St 
          =@stnow && Se=@sen", con4))
    { 
     string status="Complete";
     string sentss="Ready";
     MySqlDataAdapter ad = new MySqlDataAdapter();
     com4.Parameters.AddWithValue("@stnow", status);
     com4.Parameters.AddWithValue("@sentss", sentss);
     com4.Parameters.AddWithValue("@ID", CusID); 
     ad = new MySqlDataAdapter(com4);
     DataSet1 ds = new DataSet1();
     ad.Fill(ds.reporting_schedule);
     ReportClass report2 = new CrystalReport1();
     report2.SetDataSource(ds);
     report2.ExportToDisk
     (CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, 
     @"C:\temps\" + CusID + ".pdf"); //This is the error          
     report2.Close();
     com4.Dispose();
     ad.Dispose();
    }
  con4.close();
  }
}

如果您有任何疑问,请告诉我。

假设锁定文件的是您的任务之一,而不是某个外部进程,则可以使用 lock 语句来确保一次只有一个任务可以写入文件:

// This object is used to ensure only one task can access the file at a time
private object fileLock = new object();
private void GetReport()
{
    // previous code omitted...
    // before we try to write to the file, we wait for our lock object to become available
    lock (fileLock)
    {
        report2.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat,
            @"C:temps" + CusID + ".pdf");
    }
    // later code omitted...
}

从文档中:

lock 关键字确保一个线程不进入代码的关键部分,而另一个线程位于关键部分。如果另一个线程尝试输入锁定的代码,它将等待,阻止,直到对象被释放。

最新更新