I don’t know the Cobra so it probably makes sense
I’m just trying to learn
So, on the Cobra system you can have several applications running, I didnt know that. But wouldnt your log application run in its own thread and thereby not block other code running on the Cobra?
On the select interrupt function you use a deletefile(); function that just contains the Log.Delete() method. Why not just invoke the method directly?
Starting a new thread for each operation of the logger is not a good way of doing it. It takes time and resources. I would rather have one thread and use synchronization objects.
Look for AutoResetEvent and ManualResetEvent objects.
Use separate event object for each operation (Read,Write,etc.)
Wait for any of these events in the logger thread using WaitHandle.WaitAny.
WaitAny will return index of the event,that way you can distinguish what operation was requested. You can have another event object to signal the main thread when read operation is completed.
This kind of think is perfect for a blocking queue. A blocking queue codifies the consumer/producer pattern. A blocking queue (don’t let the name fool you), will block on empty for reader(s) and optionally block on some max number for producer thread(s). So it is perfect for a logger. I updated fezzer [url]http://www.fezzer.com/project/107/blocking-queue/[/url]. You can grab BlockingQueue class there as this sample logger. Add your file write. Logger uses a single thread to grab new items from the queue and write. Note how simple the logic becomes because most the redundant grunt work and thread safety is done in the BlockingQueue class.
using System.Threading;
using MF.Collections;
using Microsoft.SPOT;
namespace MyApp
{
public class Logger
{
private BlockingQueue q;
public Logger(int maxItems=1000)
{
q = new BlockingQueue(maxItems);
new Thread(Writer).Start();
}
public void Write(string logEntry)
{
q.Add(logEntry);
}
private void Writer()
{
while (!q.IsCompleted)
{
string item = q.Take() as string;
Debug.Print(item); // And/or write to file here.
}
Debug.Print("Logger writer thread exit.");
}
public bool IsOpen
{
get
{
return !q.IsAddingCompleted;
}
}
public void Close()
{
// Set q to complete. Allow it to drain, but no more items can be added.
q.CompleteAdding();
}
}
}
// Test Logger.
public static void TestLogger()
{
Logger l = new Logger();
for (int i = 0; i < 50; i++)
{
l.Write("Logging" + i.ToString());
}
l.Close(); // Let drain.
}
I think the lock code might be biting you since you’re calling WaitOne with it held.
It looks like you might also be losing messages if writes are being done faster than the thread can process them. (edit: you could use a queue or something to store up pending writes but even then, if the caller is hammering writes into the system, at some point the code will have to block the caller, lose messages or run out of memory.)