示例#1
0
        private void HThread_DoWork(object sender, DoWorkEventArgs e)
        {
            ThreadArg context = (ThreadArg)e.Argument;


            while (!hThread.CancellationPending)
            {
                try
                {
                    WaitHandle.WaitAny(new WaitHandle[] { context.hRecvEvent });

                    IdeMessage ideMessage;
                    int        size = Marshal.SizeOf(typeof(IdeMessage));
                    using (var accessor = context.hSharedMemory.CreateViewAccessor())
                    {
                        byte[] data = new byte[size];
                        accessor.ReadArray(0, data, 0, size);

                        IntPtr p = Marshal.AllocHGlobal(size);
                        Marshal.Copy(data, 0, p, size);

                        ideMessage = (IdeMessage)Marshal.PtrToStructure(p, typeof(IdeMessage));

                        Marshal.FreeHGlobal(p);
                    }

                    string message = HandleIdeMessage(ideMessage);
                    if (message == null)
                    {
                        continue;
                    }

                    context.hSendEvent.Set();

                    context.listBox.Invoke((MethodInvoker) delegate
                    {
                        context.listBox.Items.Add(message);
                    });
                }
                catch (Exception ex)
                {
                    continue;
                }
            }
        }
示例#2
0
        public void Initialize(ListBox listBox)
        {
            int size = Marshal.SizeOf(typeof(IdeMessage));

            hSharedMemory = MemoryMappedFile.CreateNew(SHARED_MEMORY_NAME, size);
            hRecvEvent    = new EventWaitHandle(false, EventResetMode.AutoReset, RECV_EVENT_NAME);
            hSendEvent    = new EventWaitHandle(false, EventResetMode.AutoReset, SEND_EVENT_NAME);

            ThreadArg arg = new ThreadArg();

            arg.hSendEvent    = hSendEvent;
            arg.hRecvEvent    = hRecvEvent;
            arg.hSharedMemory = hSharedMemory;
            arg.listBox       = listBox;


            hThread = new BackgroundWorker();
            hThread.WorkerSupportsCancellation = true;

            hThread.DoWork += HThread_DoWork;
            hThread.RunWorkerAsync(arg);
        }