Issues with proper displaying of a form without border with transparent
png through a custom class
I was trying to write a class which let me do read and write operation on
multiple files (like 5-10) while locking them from any kind of access.
Everytime I access a file (doesn't matter if for read or write) a new file
with the same name and a different extension is created, so other threads
(belonging to different applications) are notified of the lock (ex.
message.msg -> lock file message.lock created).
Every instance of the application will write in it's own file and read in
all other applications files (including its).
Unfortunately, when I start several instances (like 3-4) of the
application which uses this class, even if at first they look like they're
working, then in a matter or seconds / maybe a couple of minutes it looks
like one thread fails to release a file. This of course blocks the other
threads too which are unable to read that specific file.
I say this because when everything app freezes I can see a permanent .lock
file.
Of course I could put a Lock expire time (which probably would work in
this scenario), but why is this happening? To me this code looks
reasonable, but of course I'm still a newbie...so...is there any mayor
flaw in my ratio?
(Don't be scared by the length of this, they're only 2 functions and they
do pretty much the same thing, except than for the central part)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
namespace y3kMessenger
{
static class FileLockAccess
{
public static string[] readAllLines(string path)
{
bool isLocked = false;
string[] toReturn;
string lockPath = path.Replace(Global.msgExtension,
Global.lockExtension);
StreamWriter w;
//locking ...
while (!isLocked)
{
if (!File.Exists(lockPath))
{
try
{
using (w = new StreamWriter(lockPath))
{
w.WriteLine(" ");
}
isLocked = true;
}
catch (Exception e) { }
}
Thread.Sleep(10);
}
//locked, proceed with read
toReturn = File.ReadAllLines(path);
//release the lock
while (isLocked)
{
try
{
File.Delete(lockPath);
}
catch (Exception e) { }
isLocked = false;
}
return toReturn;
}
public static void writeLine(string path, string text, bool append)
{
bool isLocked = false;
string lockPath = path.Replace(Global.msgExtension,
Global.lockExtension);
StreamWriter w;
//locking ...
while (!isLocked)
{
if (!File.Exists(lockPath))
{
try
{
using (w = new StreamWriter(lockPath))
{
w.WriteLine(" ");
}
isLocked = true;
}
catch (Exception e) { }
}
Thread.Sleep(10);
}
//locked, proceed with write
using (w = new StreamWriter(path, append))
w.WriteLine(text);
//release the lock
while (isLocked)
{
try
{
File.Delete(lockPath);
}
catch (Exception e) { }
isLocked = false;
}
}
}
}
No comments:
Post a Comment