I have a solution with two projects. In the library project, I added the public static variable bool and set it to true. Then in the windows forms project, I use the flag. In the window shape designer, I added a timer, setting its interval to 1000.
I start the timer in the constructor. And then even I tick in the timer:
private void timer1_Tick(object sender, EventArgs e)
{
if (SDKHandler.Saved == true)
{
timer1.Stop();
DisplayLastTakenPhoto();
TakePhotoButton.Enabled = true;
SDKHandler.Saved = false;
timer1.Start();
}
}
And the DisplayLastTakenPhoto () method
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);
}
And the WaitForFile method
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;
}
Sometimes not all the time, but in some cases when it calls the DisplayLastTakenPhoto () method; twice in a row. Even if I stopped the timer first, I do timer1.Stop (); but still in some cases I see a method that is called twice.
And the second time it makes the program freeze and freeze sometimes even for 1-3 seconds.