Reading a Memory File before it is opened
If a consumer app attempts to open a Shared Memory File before the producer has created it, a FileNotFound Exception is thrown. A little digging didn't turn up any way to gracefully test/check for a MemoryMappedFile before trying to open it (or even better get some kind of file watcher or WaitEvent for it to show up).
So I used this function, but it feels like it belongs in the library somewhere:
static Boolean TryOpenExisting(out SharedMemory.CircularBuffer buf, String name, TimeSpan ts)
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
if (ts.TotalMilliseconds > 0) { sw.Start(); }
do
{
try
{
buf = new SharedMemory.CircularBuffer(name);
return true;
}
catch (System.IO.FileNotFoundException e)
{
buf = null;
}
catch (Exception e)
{
throw e;
}
} while (sw.Elapsed < ts);
return (buf != null);
}
Here's how I used it in the consumer code:
if (consumer == null) {
TryOpenExisting(out consumer, name: "MySharedMemory", ts: TimeSpan.FromSeconds(5f));
if (consumer != null) { cbuf = new byte[consumer.NodeBufferSize]; }
}
if (consumer != null)
{
while ((consumer.Read<byte>(cbuf) > 0)) {
........
}
}
Good idea, I'll implement a wait event tho for it.
@MikeFair Best to keep the conversation over in the other issue (#7), but these are all ideas worth exploring. There are a number of uses for the base underlying class, we can always create variations that support the different scenarios, or else via configuration.
@spazzarama Good point; I deleted that comment to keep this and #7 separated (I've also got a better idea on how to go about handling #7 now). :)