SharedMemory icon indicating copy to clipboard operation
SharedMemory copied to clipboard

Reading a Memory File before it is opened

Open MikeFair opened this issue 10 years ago • 3 comments

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)) {
                        ........
                    }
                }

MikeFair avatar Feb 03 '16 07:02 MikeFair

Good idea, I'll implement a wait event tho for it.

justinstenning avatar Feb 03 '16 07:02 justinstenning

@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.

justinstenning avatar Feb 03 '16 08:02 justinstenning

@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). :)

MikeFair avatar Feb 20 '16 18:02 MikeFair