/// <summary>
        /// Connect to a named pipe
        /// </summary>
        /// <param name="pipeName">The pipe name to connect</param>
        public void Connect(string pipeName)
        {
            if (_isRunning)
            {
                throw new AlreadyRunningException("The client is already running");
            }
            _pipeName   = pipeName;
            _pipeStream = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
            NamedPipeClientStream clientStream = _pipeStream as NamedPipeClientStream;

            _isRunning = true;
            try
            {
                clientStream.Connect(0);
                if (clientStream.IsConnected)
                {
                    NotifyStatusChanged(ClientStatus.Connected);
                }
            }
            catch (System.IO.IOException)
            {
                clientStream.Dispose();
                _isRunning  = false;
                _pipeStream = null;
                throw new Exception("The server is connected to another client");
            }
            catch
            {
                NotifyStatusChanged(ClientStatus.Connecting);
            }
            _taskScheduler = new SingleThreadTaskScheduler();
            _workThread    = ThreadEx.Start(ConnectProc);
        }
Exemple #2
0
        /// <summary>
        /// Start udp server listening on a specific port and join a mulitcast group.
        /// </summary>
        /// <param name="multicastAddress">The multicast address to join.</param>
        /// <param name="nPort">The listening port of the server.</param>
        public void Start(string multicastAddress, ushort nPort)
        {
            if (_isRunning)
            {
                throw new AlreadyRunningException(Constants.ExMessageServerAlreadyRunning);
            }
            if (nPort <= 0 || nPort >= 65535)
            {
                throw new ArgumentException("invalid port number");
            }
            _serverPort = nPort;
            try
            {
                _listenEndPoint = new IPEndPoint(IPAddress.Any, _serverPort);
                _udpServer      = new UdpClient(_listenEndPoint);
                _udpSender      = new UdpClient();
                if (!string.IsNullOrEmpty(multicastAddress))
                {
                    _multicastAddress = multicastAddress;
                    _udpServer.JoinMulticastGroup(IPAddress.Parse(multicastAddress));
                }

                _taskScheduler = new SingleThreadTaskScheduler();
                _recvThread    = ThreadEx.Start(RecvProc);
            }
            catch (System.Exception ex)
            {
                if (_udpServer != null)
                {
                    _udpServer.Close();
                }
                throw new Exception("udp server start failed." + ex.Message);
            }
        }
Exemple #3
0
 public LogWorker(string fileName, Encoding encodingType = null)
     : base(encodingType)
 {
     m_fileName = fileName;
     m_thread   = new ThreadEx(this.Execute, ThreadPriority.Normal);
     m_thread.Start();
 }
        public void ProcessBeginRequest()
        {
            UploadFileBeginResponse response = new UploadFileBeginResponse()
            {
                AllowUpload     = true,
                RequestID       = LastRequestID,
                UploadSessionID = UploadSessionID
            };

            if (IsRunning)
            {
                response.AllowUpload = false;
                response.Message     = "can not upload a new file because the last uploading is running.";
                _tcpServer.SendModelMessage(ClientID, response);
                return;
            }

            try
            {
                _fileStream = File.Open(SavePath, FileMode.Create, FileAccess.Write);
            }
            catch (Exception ex)
            {
                response.AllowUpload = false;
                response.Message     = ex.Message;
                _tcpServer.SendModelMessage(ClientID, response);
                return;
            }

            _tcpServer.SendModelMessage(ClientID, response);
            _isRunning = true;
            _cancelWaitEvent.Reset();
            _lastActiveTime = DateTime.Now;
            _cancelThread   = ThreadEx.Start(CancelProc);
        }
Exemple #5
0
 public RVList <LNode> ProcessFileWithThreadAbort(InputOutput io, Action <InputOutput> onProcessed, TimeSpan timeout)
 {
     if (timeout == TimeSpan.Zero || timeout == TimeSpan.MaxValue)
     {
         return(ProcessFile(io, onProcessed));
     }
     else
     {
         Exception ex     = null;
         var       thread = new ThreadEx(() =>
         {
             try { ProcessFile(io, null); }
             catch (Exception e) { ex = e; ex.PreserveStackTrace(); }
         });
         thread.Start();
         if (thread.Join(timeout))
         {
             onProcessed(io);
         }
         else
         {
             io.Output = new RVList <LNode>(F.Id("processing_thread_timed_out"));
             thread.Abort();
             thread.Join(timeout);
         }
         if (ex != null)
         {
             throw ex;
         }
         return(io.Output);
     }
 }
Exemple #6
0
 private void AfterConnect(bool isConnected)
 {
     if (!_isRunning)
     {
         return;
     }
     if (isConnected)
     {
         AddNewClient(_clientSocket);
     }
     else
     {
         _clientSocket.Close();
         _clientSocket.Dispose();
         if (!_autoReconnect)
         {
             _isRunning = false;
             SetStatusAndNotify(ClientStatus.Closed);
         }
         else
         {
             //if auto reconnect is used, we should do reconnect
             ThreadEx.Start(() =>
             {
                 //reconnect to server 2 seconds later
                 _reconnectWaitEvent.WaitOne(2000);
                 if (_isRunning)
                 {
                     InitClientSocket();
                     ConnectAsyncInner(null);
                 }
             });
         }
     }
 }
Exemple #7
0
 public TaskThread(ITask initialTask, TaskRunner runner)
 {
     Task   = initialTask;
     Thread = new ThreadEx(TestThread);
     Runner = runner;
     Thread.Start();
 }
Exemple #8
0
        protected override void OnClientStatusChanged(bool isInThread, ClientStatusChangedEventArgs args, HashSet <string> groups)
        {
            ClientStatus status = args.Status;

            if (status == ClientStatus.Connected)
            {
                SetStatusAndNotify(status);
            }
            else if (status == ClientStatus.Closed)
            {
                if (!_autoReconnect)
                {
                    _isRunning = false;
                    //if (isInThread)
                    //{
                    //    _syncContext.Post((state) =>
                    //    {
                    //        SetStatusAndNotify(ClientStatus.Closed);
                    //    }, null);
                    //}
                    //else
                    //{
                    //    SetStatusAndNotify(ClientStatus.Closed);
                    //}
                    SetStatusAndNotify(ClientStatus.Closed);
                }
                else
                {
                    if (!_isRunning)
                    {
                        SetStatusAndNotify(ClientStatus.Closed);
                        //_syncContext.Post((state) =>
                        //{
                        //    SetStatusAndNotify(ClientStatus.Closed);
                        //}, null);
                        return;
                    }

                    SetStatusAndNotify(ClientStatus.Connecting);
                    //_syncContext.Post((state) =>
                    //{
                    // AfterConnect(false);
                    //SetStatusAndNotify(ClientStatus.Connecting);
                    ThreadEx.Start(() =>
                    {
                        //reconnect to server 2 seconds later
                        _reconnectWaitEvent.WaitOne(2000);

                        if (_isRunning)
                        {
                            InitClientSocket();
                            ConnectAsyncInner(null);
                        }
                    });
                    //}, null);
                }
            }
        }
Exemple #9
0
        public void BasicChecks()
        {
            ThreadLocalVariable <int> threadVar = new ThreadLocalVariable <int>(123);
            Thread parent = Thread.CurrentThread;
            bool   eventOccurred = false;
            bool   valueOk = true, eventOk = true;
            bool   stop    = false;
            bool   started = false;

            ThreadEx t = new ThreadEx(delegate(object o)
            {
                started = true;
                try
                {
                    if ((int)o != 123 || threadVar.Value != 123)
                    {
                        valueOk = false;
                    }
                }
                catch
                {
                    valueOk = false;
                }
                while (!stop)
                {
                    GC.KeepAlive("");                     // Waste time
                }
                started = false;
            });

            EventHandler <ThreadStartEventArgs> eh = null;

            ThreadEx.ThreadStarting += (eh = delegate(object o, ThreadStartEventArgs e)
            {
                eventOccurred = true;
                if (e.ChildThread != t || e.ParentThread != parent)
                {
                    eventOk = false;
                }
                ThreadEx.ThreadStarting -= eh;
            });

            Assert.IsFalse(t.IsAlive);
            Assert.AreEqual(System.Threading.ThreadState.Unstarted, t.ThreadState);
            t.Start(123);
            Assert.IsTrue(t.IsAlive);
            Assert.IsTrue(eventOccurred);
            Assert.IsTrue(eventOk);
            while (!started)
            {
                ThreadEx.Sleep(0);
            }
            Assert.AreEqual(System.Threading.ThreadState.Running, t.ThreadState);
            stop = true;
            Assert.IsTrue(t.Join(5000));
            Assert.IsTrue(valueOk);
            Assert.IsFalse(started);
        }
Exemple #10
0
        private void AddCopyRevDataThread(bool isStart)
        {
            var copyRevDataThread = new ThreadEx(this.CopyRevDataThreadMethod, $"拷贝数据线程[{this._copyRevDataThreads.Count}]", true);

            if (isStart)
            {
                Loger.Warn("添加一个用于拷贝接收到数据的线程[接收数据不及时,可能有数据被覆盖]");
                copyRevDataThread.Start();
            }

            this._copyRevDataThreads.Add(copyRevDataThread);
        }
Exemple #11
0
        private void btnThreadEx_Click(object sender, RoutedEventArgs e)
        {
            if (_thread != null)
            {
                _thread.Stop();
                _thread.Dispose();
                _thread = null;
                return;
            }

            _thread = new ThreadEx(ThreadMethod, "xx", true);
            _thread.Start();
        }
Exemple #12
0
 /// <summary>
 /// Start pipe server using a specific name.
 /// </summary>
 /// <param name="pipeName">The pipe name for starting a pipe server.</param>
 public void Start(string pipeName)
 {
     if (_isRunning)
     {
         throw new AlreadyRunningException("The server is already running");
     }
     if (string.IsNullOrWhiteSpace(pipeName))
     {
         throw new ArgumentException("Pipe name is required");
     }
     _pipeName      = pipeName;
     _taskScheduler = new SingleThreadTaskScheduler();
     _pipeStream    = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
     _workThread    = ThreadEx.Start(WorkProc);
 }
        /// <summary>
        /// Initiates a worker thread to listen for NDIS-reported
        /// changes to the status of the adapter.  Listeners can
        /// register for notification of these changes, which the
        /// thread will send.
        /// </summary>
        public void StartStatusMonitoring()
        {
            if (!Active)
            {
                // Create a point-to-point message queue to get the
                // notifications.
                mq = new PointToPointMsgQueue(
                    null,                       // unnamed
                    25, NDISUIO_DEVICE_NOTIFICATION.Size,
                    true, 0);

                // Start monitoring thread.
                mqt = new ThreadEx(new ThreadStart(this.StatusThread));
                mqt.Start();
            }
        }
Exemple #14
0
        /// <summary>
        /// Initiates a worker thread to listen for reports of device
        /// changes.  Listeners can register for notification of these
        /// changes, which the thread will send.
        /// </summary>
        public void StartStatusMonitoring()
        {
            if (!Active)
            {
                // Create a point-to-point message queue to get the
                // notifications.
                mq = new PointToPointMsgQueue(
                    null,                       // unnamed
                    25, DEVDETAIL.MAX_DEVDETAIL_SIZE,
                    true, 0);

                // Start monitoring thread.
                mqt = new ThreadEx(new ThreadStart(this.StatusThread));
                mqt.Start();
            }
        }
Exemple #15
0
        private void AddParseDispoatchThread()
        {
            try
            {
                lock (this._parseDataThreadsLock)
                {
                    if (this._parseDataThreads.Count >= this._config.ParseDataMaxThreadCount)
                    {
                        return;
                    }

                    var parseDataThread = new ThreadEx(this.ProReceiveDataThreadMethod, $"解析数据线程方法[{this._index++}]", true);
                    parseDataThread.Start();
                    this._parseDataThreads.Add(parseDataThread);
                }
            }
            catch (ObjectDisposedException)
            { }
        }
Exemple #16
0
        // ******************************************************************
        public static DlgProgress CreateProgressBar(Window owner, DlgProgressModel dlgProgressModel)
        {
            DlgProgress dlgProgressWithProgressStatus     = null;
            var         listDlgProgressWithProgressStatus = new List <DlgProgress>();
            var         resetEvent = new AutoResetEvent(false);

            IntPtr windowHandleOwner = new WindowInteropHelper(owner).Handle;

            dlgProgressModel.Owner       = owner;
            dlgProgressModel.IntPtrOwner = windowHandleOwner;

            var workerThread = new ThreadEx(() => StartDlgProgress(dlgProgressModel, resetEvent, listDlgProgressWithProgressStatus));

            workerThread.Thread.SetApartmentState(ApartmentState.STA);
            workerThread.Start();
            resetEvent.WaitOne(10000);
            if (listDlgProgressWithProgressStatus.Count > 0)
            {
                dlgProgressWithProgressStatus = listDlgProgressWithProgressStatus[0];
            }

            return(dlgProgressWithProgressStatus);
        }
Exemple #17
0
 public LogWorker(LogWorker b)
     : base(b)
 {
     m_fileName = b.FileName;
     m_thread.Start();
 }
 /// <summary>
 /// Open the share memory
 /// </summary>
 public new void Open()
 {
     base.Open();
     _taskScheduler = new SingleThreadTaskScheduler();
     _recvThread    = ThreadEx.Start(RecvProc);
 }
Exemple #19
0
        [STAThread]         // Required by ICSharpCode.TextEditor
        public static void Main(string[] args)
        {
            BMultiMap <string, string> options = new BMultiMap <string, string>();

            var argList = args.ToList();

            UG.ProcessCommandLineArguments(argList, options, "", ShortOptions, TwoArgOptions);
            if (!options.ContainsKey("nologo"))
            {
                Console.WriteLine("LeMP macro compiler (pre-alpha)");
            }

            string _;

            if (options.TryGetValue("help", out _) || options.TryGetValue("?", out _))
            {
                ShowHelp(KnownOptions.OrderBy(p => p.Key));
                return;
            }
            if (options.ContainsKey("editor"))
            {
                Console.WriteLine("Starting editor...");
                System.Windows.Forms.Application.EnableVisualStyles();
                System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
                System.Windows.Forms.Application.Run(new TextEditor.LempDemoForm());
                return;
            }

            Severity minSeverity = Severity.Note;

                        #if DEBUG
            minSeverity = Severity.Debug;
                        #endif
            var filter = new SeverityMessageFilter(MessageSink.Console, minSeverity);

            Compiler c = ProcessArguments(options, filter, typeof(Macros), argList);
            Compiler.WarnAboutUnknownOptions(options, MessageSink.Console, KnownOptions);
            if (c != null)
            {
                c.AddMacros(typeof(global::LeMP.StandardMacros).Assembly);
                c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP.Prelude"));
                c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP"));
                using (LNode.PushPrinter(Ecs.EcsNodePrinter.PrintPlainCSharp))
                    c.Run();
            }
            else if (args.Length == 0)
            {
                ShowHelp(KnownOptions.OrderBy(p => p.Key));

                Console.WriteLine();
                Console.WriteLine("LeMP started without arguments. Starting editor (--editor)");

                var thread = new ThreadEx(() => {
                    System.Windows.Forms.Application.EnableVisualStyles();
                    System.Windows.Forms.Application.Run(new TextEditor.LempDemoForm());
                });
                thread.Thread.SetApartmentState(ApartmentState.STA);
                thread.Start();

                Console.WriteLine("Press Enter to run unit tests. Using the editor? Keep the terminal open.");
                Console.ReadLine();

                RunTests.Run(new Loyc.Syntax.Lexing.TokenTests());
                RunTests.Run(new Loyc.Syntax.Les.LesLexerTests());
                RunTests.Run(new Loyc.Syntax.Les.LesParserTests());
                RunTests.Run(new Loyc.Syntax.Les.LesPrinterTests());
                RunLeMPTests();
                Ecs.Program.RunEcsTests();
            }
        }