tiesky.com.SharmIpcInternals.ReaderWriterHandler.InitReader C# (CSharp) Method

InitReader() private method

private InitReader ( ) : void
return void
        unsafe void InitReader()
        {
            string prefix = sm.instanceType == eInstanceType.Slave ? "1" : "2";

            if (ewh_Reader_ReadyToRead == null)
            {

                ewh_Reader_ReadyToRead = new EventWaitHandle(false, EventResetMode.ManualReset, sm.uniqueHandlerName + prefix + "_SharmNet_ReadyToRead");
                ewh_Reader_ReadyToWrite = new EventWaitHandle(true, EventResetMode.ManualReset, sm.uniqueHandlerName + prefix + "_SharmNet_ReadyToWrite");
                ewh_Reader_ReadyToWrite.Set();
            }

            //if (sm.instanceType == tiesky.com.SharmIpc.eInstanceType.Slave)
            //{
            //    Console.WriteLine("My reader handlers:");
            //    Console.WriteLine(sm.uniqueHandlerName + prefix + "_SharmNet_ReadyToRead");
            //    Console.WriteLine(sm.uniqueHandlerName + prefix + "_SharmNet_ReadyToWrite");
            //    Console.WriteLine("-------");
            //}

            if (Reader_mmf == null)
            {
                //Reader_mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateOrOpen(sm.uniqueHandlerName + prefix + "_SharmNet_MMF", sm.bufferCapacity, MemoryMappedFileAccess.ReadWrite);
                //Reader_accessor = Reader_mmf.CreateViewAccessor(0, sm.bufferCapacity);

                var security = new MemoryMappedFileSecurity();
                security.AddAccessRule(new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>(
                    new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null),
                    MemoryMappedFileRights.FullControl,
                    System.Security.AccessControl.AccessControlType.Allow));
                //Reader_mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateOrOpen(@"Global\MapName1", sm.bufferCapacity,
                Reader_mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateOrOpen(sm.uniqueHandlerName + prefix + "_SharmNet_MMF", sm.bufferCapacity,
                    MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.DelayAllocatePages, security, System.IO.HandleInheritability.Inheritable);

                Reader_accessor = Reader_mmf.CreateViewAccessor(0, sm.bufferCapacity);
                Reader_accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref Reader_accessor_ptr);
            }

            Task.Run(() =>
            {
                byte[] hdr = null;
                byte[] ret=null;
                ushort iCurChunk = 0;
                ushort iTotChunk = 0;
                ulong iMsgId = 0;
                int iPayLoadLen = 0;
                ulong iResponseMsgId = 0;

                eMsgType msgType = eMsgType.RpcRequest;

                try
                {
                    while (true)
                    {
                        ewh_Reader_ReadyToRead.WaitOne();
                        if (ewh_Reader_ReadyToRead == null) //Special Dispose case
                            return;
                        ewh_Reader_ReadyToRead.Reset();
                        //Reading data from MMF

                        //Reading header
                        hdr = ReadBytes(Reader_accessor_ptr, 0, protocolLen);
                        msgType = (eMsgType)hdr[0];

                        //Parsing header
                        switch (msgType)
                        {
                            case eMsgType.ErrorInRpc:

                                iPayLoadLen = BitConverter.ToInt32(hdr, 9); //+4
                                iResponseMsgId = BitConverter.ToUInt64(hdr, 17); //+8

                                this.sm.SharmIPC.InternalDataArrived(msgType, iResponseMsgId, null);
                                break;

                            case eMsgType.RpcResponse:
                            case eMsgType.RpcRequest:
                            case eMsgType.Request:

                                bool zeroByte = false;
                                iMsgId = BitConverter.ToUInt64(hdr, 1); //+8
                                iPayLoadLen = BitConverter.ToInt32(hdr, 9); //+4
                                if (iPayLoadLen == Int32.MaxValue)
                                {
                                    zeroByte = true;
                                    iPayLoadLen = 0;
                                }
                                iCurChunk = BitConverter.ToUInt16(hdr, 13); //+2
                                iTotChunk = BitConverter.ToUInt16(hdr, 15); //+2
                                iResponseMsgId = BitConverter.ToUInt64(hdr, 17); //+8

                                if (iCurChunk == 1)
                                {
                                    chunksCollected = null;
                                    MsgId_Received = iMsgId;
                                }
                                else if (iCurChunk != currentChunk + 1)
                                {
                                    //Wrong income, sending special signal back, waiting for new MsgId
                                    switch (msgType)
                                    {
                                        case eMsgType.RpcRequest:
                                            this.SendMessage(eMsgType.ErrorInRpc, this.GetMessageId(), null, iMsgId);
                                            break;
                                        case eMsgType.RpcResponse:
                                            this.sm.SharmIPC.InternalDataArrived(eMsgType.ErrorInRpc, iResponseMsgId, null);
                                            break;
                                    }
                                    break;
                                }

                                if (iTotChunk == iCurChunk)
                                {
                                    if (chunksCollected == null)
                                        this.sm.SharmIPC.InternalDataArrived(msgType, (msgType == eMsgType.RpcResponse) ? iResponseMsgId : iMsgId, iPayLoadLen == 0 ? ((zeroByte) ? new byte[0] : null) : ReadBytes(Reader_accessor_ptr, protocolLen, iPayLoadLen));
                                    else
                                    {
                                        ret = new byte[iPayLoadLen + chunksCollected.Length];
                                        Buffer.BlockCopy(chunksCollected, 0, ret, 0, chunksCollected.Length);
                                        Buffer.BlockCopy(ReadBytes(Reader_accessor_ptr, protocolLen, iPayLoadLen), 0, ret, chunksCollected.Length, iPayLoadLen);
                                        this.sm.SharmIPC.InternalDataArrived(msgType, (msgType == eMsgType.RpcResponse) ? iResponseMsgId : iMsgId, ret);
                                    }
                                    chunksCollected = null;
                                    currentChunk = 0;
                                }
                                else
                                {
                                    if (chunksCollected == null)
                                    {
                                        chunksCollected = ReadBytes(Reader_accessor_ptr, protocolLen, iPayLoadLen);
                                    }
                                    else
                                    {

                                        byte[] tmp = new byte[chunksCollected.Length + iPayLoadLen];
                                        Buffer.BlockCopy(chunksCollected, 0, tmp, 0, chunksCollected.Length);
                                        Buffer.BlockCopy(ReadBytes(Reader_accessor_ptr, protocolLen, iPayLoadLen), 0, tmp, chunksCollected.Length, iPayLoadLen);
                                        chunksCollected = tmp;
                                    }

                                    currentChunk = iCurChunk;
                                }
                                break;
                            default:
                                //Unknown protocol type
                                chunksCollected = null;
                                currentChunk = 0;
                                //Wrong income, doing nothing
                                throw new Exception("tiesky.com.SharmIpc: Reading protocol contains errors");
                                //break;
                        }

                        //Setting signal
                        ewh_Reader_ReadyToWrite.Set();
                    }
                }
                catch(System.Exception ex)
                {
                    /*
                    System.ObjectDisposedException: Das SafeHandle wurde geschlossen. bei System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
                    bei System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
                    bei Microsoft.Win32.Win32Native.SetEvent(SafeWaitHandle handle) bei System.Threading.EventWaitHandle.Set() bei tiesky.com.SharmIpcInternals.ReaderWriterHandler.b__28_0()
                    */
                    this.sm.SharmIPC.LogException("SharmIps.ReaderWriterHandler.InitReader LE", ex);
                }

            });
        }