我正在打印PrintDocument
到PDF.I然后将这个PDF存储在MS SQL表中。我必须确保在将文档插入列之前“打印”该文档。我有以下代码检查文件是否“可用”:
public static bool IsFileReady(String sFilename)
{
try
{
using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None))
{
if (inputStream.Length > 0)
{
return true;
}
else
{
return false;
}
}
}
catch (Exception)
{
return false;
}
}
我想为其花费的时间或检查文件是否准备好的次数添加某种上限。如果打印机出现故障,则线程将永远等待。我该如何实现它?
答案 0 :(得分:2)
如果达到最大重试次数或已经过了最长时间,则此代码退出循环:
private const int MAX_RETRIES = 100;
private const int MAX_RETRY_SECONDS = 120;
public static bool IsFileReady(String sFilename)
{
int tryNumber = 0;
DateTime endTime = DateTime.Now + new TimeSpan(0, 0, MAX_RETRY_SECONDS);
while (tryNumber < MAX_RETRIES && DateTime.Now < endTime)
{
try
{
using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None))
{
if (inputStream.Length > 0)
{
return true;
}
}
}
catch (Exception)
{
//Swallow Exception
}
//Slow down the looping
System.Threading.Thread.Sleep(500);
tryNumber += 1;
}
return false;
}