【发布时间】:2016-03-22 11:21:28
【问题描述】:
我有两个项目的解决方案。 在一个库项目中,我添加了一个公共静态布尔变量并将其设置为 true。 然后在 Windows 窗体项目中,我使用了该标志。 在 windows 窗体项目设计器中,我添加了一个计时器,将其间隔设置为 1000。
我正在构造函数中启动计时器。 然后在计时器滴答声中,即使我正在做:
private void timer1_Tick(object sender, EventArgs e)
{
if (SDKHandler.Saved == true)
{
timer1.Stop();
DisplayLastTakenPhoto();
TakePhotoButton.Enabled = true;
SDKHandler.Saved = false;
timer1.Start();
}
}
还有 DisplayLastTakenPhoto() 方法
private void DisplayLastTakenPhoto()
{
string mypath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "RemotePhoto");
var directory = new DirectoryInfo(mypath);
var myFile = directory.EnumerateFiles()
.Where(f => f.Extension.Equals(".jpg", StringComparison.CurrentCultureIgnoreCase) || f.Extension.Equals("raw", StringComparison.CurrentCultureIgnoreCase))
.OrderByDescending(f => f.LastWriteTime)
.First();
if (WaitForFile(myFile.FullName) == true) LiveViewPicBox.Load(myFile.FullName);
}
还有 WaitForFile 方法
bool WaitForFile(string fullPath)
{
int numTries = 0;
while (true)
{
++numTries;
try
{
using (FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 100))
{
fs.ReadByte();
break;
}
}
catch (Exception ex)
{
if (numTries > 10)
{
return false;
}
System.Threading.Thread.Sleep(500);
}
}
return true;
}
有时并非一直如此,但在某些情况下,当它调用方法 DisplayLastTakenPhoto();连续两次。即使我先停止计时器,我也在做 timer1.Stop();但在某些情况下,我仍然看到该方法被调用了两次。
第二次它使程序挂起/冻结有时甚至 1-3 秒。
【问题讨论】:
-
这是什么定时器?它看起来像一个表单计时器?
-
同样如此。这是我从设计器的工具箱中拖出来的窗体计时器。
-
在上面下个断点,看看为什么会被调用两次。