justinstenning / SharedMemory

C# shared memory classes for sharing data between processes (Array, Buffer and Circular Buffer)
https://www.nuget.org/packages/SharedMemory
Other
569 stars 119 forks source link

Reading a Memory File before it is opened #6

Open MikeFair opened 8 years ago

MikeFair commented 8 years ago

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)) {
                        ........
                    }
                }
justinstenning commented 8 years ago

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

justinstenning commented 8 years ago

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

MikeFair commented 8 years ago

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