المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Processes (up to 4) accessing to "serial.log" file handling



C# Programming
08-24-2009, 10:36 PM
I've had success having an individual (one at a time) to perform reading serial number from the file and increment by one and save the new number in this .log file.

However is that I'm trying to determine the best approach for each process to wait for the file access while one of the process is using the file. Once the file is ready for read/write, then the other process can use the file.

Sample code for each process (pretty much the same for the 4 processes:

--------

private void RunProcess1()
{
while (fileHandle != IntPtr.Zero)
{
lblStatus1.BackColor = Color.Yellow;
lblStatus1.Text = "Awaiting Accessing Serial file...";
Application.DoEvents();

for (int m = 0; m < 100000; m++)
Application.DoEvents();
}

//do
//{
try
{
lblStatus1.BackColor = Color.Magenta;
lblStatus1.Text = "Accessing Serial file";
Application.DoEvents();
FileStream filestream = new FileStream("serial.log", FileMode.OpenOrCreate, FileAccess.Read, FileShare.None);
fileHandle = filestream.Handle;
StreamReader tr = new StreamReader(filestream);
count = Convert.ToInt32(tr.ReadLine(), 10);
lblSerial1.Text = count.ToString();
tr.Close();

lblStatus1.BackColor = Color.Lime;
lblStatus1.Text = "Saving Serial file";
Application.DoEvents();

filestream = new FileStream("serial.log", FileMode.Create, FileAccess.Write, FileShare.None);
StreamWriter sw = new StreamWriter(filestream);
sw.Write(++count);
sw.Flush();
lblStatus1.BackColor = Color.Green;

for (int m = 0; m < 1000000; m++)
Application.DoEvents();

sw.Close();

lblStatus1.BackColor = defaultBackground;
lblStatus1.Text = "Success!";
Application.DoEvents();
//timer1.Start();
fileHandle = IntPtr.Zero;
}
catch (Exception err)
{
//timer1.Stop();
//proc1Success = false;
}

//} while (proc1Success == false);
}