我有兩個項目的解決方案。 在一個庫項目中,我添加了一個公共靜態布爾變量,並將其設置爲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;
}
Somtimes不是所有的時間,但在某些情況下,當它調用DisplayLastTakenPhoto()方法時;連續兩次。即使我先停下了計時器,我正在做timer1.Stop();但仍然在某些情況下,我看到了兩次調用的方法。
第二次,它使程序掛起/凍結有時甚至1-3秒。
它是什麼樣的計時器?它看起來像一個表格計時器? – Equalsk
Equalsk它是。這是Windows窗體計時器,我把它從設計器的工具箱中拖出來。 –
在它上面放置一個斷點,看看它爲什麼被調用兩次。 – Ben