Ejemplo n.º 1
0
 public LogWorker(string fileName, Encoding encodingType = null)
     : base(encodingType)
 {
     m_fileName = fileName;
     m_thread   = new ThreadEx(this.Execute, ThreadPriority.Normal);
     m_thread.Start();
 }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 3
0
 public TaskThread(ITask initialTask, TaskRunner runner)
 {
     Task   = initialTask;
     Thread = new ThreadEx(TestThread);
     Runner = runner;
     Thread.Start();
 }
Ejemplo n.º 4
0
        //各网站行情信息:
        private void GetCheckVersion(Object o, EventArgs e)
        {
            if (Define.NewVersionUrl != "")
            {
                DialogResult dr;
                dr = MessageBox.Show("发现新版本,是否现在升级?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr == DialogResult.No)
                {
                    Data.GetLoginResult = Define.Login_Falied;
                    this.Close();
                    return;
                }

                label_updatealert.Text = "正在下载升级包。";

                txt_Username.Enabled = false;
                txt_password.Enabled = false;
                button1.Enabled = false;
                linkLabel3.Enabled = false;
                linkLabel4.Enabled = false;

                label_updatealert.Visible = true;

                ThreadEx threadex = new ThreadEx();
                threadex.Start(new ThreadStart(threadex.GetNewVersion), new EventHandler(GetNewVersion), this);
            }
        }
Ejemplo n.º 5
0
        /// <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);
        }
Ejemplo n.º 6
0
        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);
        }
Ejemplo n.º 7
0
        //private void PlayForward(MediaFrame frame)
        //{
        //    if (frame != null)
        //    {
        //        if (frame.nTimetick < _curPlayMediaTimetick)
        //        {
        //            _isHasBFrame = true;
        //        }
        //        if (_curPlayMediaTimetick < frame.nTimetick)
        //            _curPlayMediaTimetick = frame.nTimetick;
        //    }

        //    if (frame != null)
        //    {
        //        if (!_isHasBFrame)
        //        {
        //            if (Speed == 1)
        //            {
        //                var sleep = (int)(_syncPlayTime);
        //                //if (_queue.Count > (4 + errorsleep))
        //                //{
        //                //    errorsleep +=1;
        //                //    iptvdefaultsleep -= 4;
        //                //}

        //                if (queueCount>6)
        //                {

        //                   // errorsleep = decsleep / 2 + decsleep % 2;
        //                    //if (decsleep != 0)
        //                    //    iptvdefaultsleep -= decsleep / 2 ;
        //                    //else
        //                        iptvdefaultsleep -= 1;// +errorsleep % 2;
        //                    min = iptvdefaultsleep;
        //                    decsleep = 0;
        //                    errorsleep += 1;
        //                }

        //                if (_queue.Count <3)
        //                {
        //                    // decsleep = errorsleep / 2 + errorsleep % 2;
        //                    if (errorsleep != 0)
        //                    {
        //                        iptvdefaultsleep += errorsleep / 2;
        //                    }
        //                    else
        //                        iptvdefaultsleep += 1;// +decsleep % 2; ;
        //                    max = iptvdefaultsleep;

        //                    errorsleep = 0;
        //                    decsleep++;
        //                }

        //                if (iptvdefaultsleep > 100)
        //                {
        //                    iptvdefaultsleep = 100;
        //                }

        //                if (iptvdefaultsleep * queueCount > 1000)
        //                {
        //                    iptvdefaultsleep -= 1;
        //                }

        //                if (iptvdefaultsleep <= 0)
        //                    iptvdefaultsleep = (min + max) / 2 <= 0 ? 40 : (min + max) / 2;
        //                //if (iptvdefaultsleep>40)
        //                //    iptvdefaultsleep = 40;
        //                Thread.Sleep(iptvdefaultsleep);
        //                //Console.Clear();
        //                //Console.WriteLine("tick:" + iptvdefaultsleep + " cachecount:" + queueCount + " lastcount:" + lastcount + " sleep:" + sleep);
        //                lastcount = queueCount;
        //                _lastPlayMediaTimetick = frame.nTimetick;

        //                //}
        //                //else
        //                //{
        //                //    var sleep = (int)((frame.nTimetick - _syncPlayTime));
        //                //    if (sleep > 200)
        //                //        sleep = 40;
        //                //    if (sleep < 0)
        //                //        sleep = 0;
        //                //    Thread.Sleep(sleep);
        //                //    _lastPlayMediaTimetick = frame.nTimetick;
        //                //}
        //            }
        //            else
        //            {
        //                var sysSpan = Environment.TickCount - _lastPlaySystemTime;
        //                var sleep = (int)((frame.nTimetick - _lastPlayMediaTimetick - sysSpan) / Speed);
        //                if (sleep > 200 || sleep < 0)
        //                    sleep = 40;
        //                Thread.Sleep(sleep);
        //                _lastPlayMediaTimetick = frame.nTimetick;
        //            }
        //        }
        //        if (!CheckInit(frame))
        //            return;

        //        _lastPlaySystemTime = Environment.TickCount;

        //        byte[] yuv = _ffimp.VideoDec(frame.Data, _yuvDataBuffer);

        //        //_drawHandle.BeginInvoke(frame.Data, null, null);

        //        Draw(yuv);

        //    }
        //    else
        //    {
        //        ThreadEx.Sleep(10);
        //    }

        //}

        private void PlayBackward(MediaFrame frame)
        {
            if (frame != null)
            {
                if (frame.nIsKeyFrame == 1)
                {
                    if (_stackRewindFrame != null)
                    {
                        _stackRewindFrame.Push(frame);
                        PlayBackward(_stackRewindFrame);
                    }
                    _stackRewindFrame = new Stack <MediaFrame>();
                }
                else
                {
                    if (_stackRewindFrame == null)
                    {
                        _stackRewindFrame = new Stack <MediaFrame>();
                    }
                    _stackRewindFrame.Push(frame);
                }
                _PlayBackwardResetPos = false;
            }
            else
            {
                ThreadEx.Sleep(10);
            }
        }
Ejemplo n.º 8
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);
     }
 }
 protected override void NewMediaFrame(MediaFrame frame)
 {
     if (_firstTimeTick == 0 && frame.nIsKeyFrame == 1 && frame.nIsAudio == 0)
     {
         _firstTimeTick = frame.nTimetick;
         _startTimeTick = DateTime.Now.Ticks / 10000;
     }
     if (_firstTimeTick == 0)
     {
         return;
     }
     if (_lastTimeTick <= frame.nTimetick)
     {
         _lastTimeTick = frame.nTimetick;
         var span  = DateTime.Now.Ticks / 10000 - _startTimeTick;
         int sleep = (int)((_lastTimeTick - _firstTimeTick) - span);
         //Console.WriteLine((_lastTimeTick - _firstTimeTick) + "   " + span);
         if (sleep > 40)
         {
             sleep = 40;
         }
         if (PlaySync)
         {
             if (sleep > 0)
             {
                 ThreadEx.Sleep(sleep);
             }
         }
     }
     base.NewMediaFrame(frame);
 }
Ejemplo n.º 10
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);
                 }
             });
         }
     }
 }
Ejemplo n.º 11
0
        public void ZeroCodeLengthZipFile()
        {
            Assert.Throws <SharpZipBaseException>(() => {
                Exception threadException = null;
                var testThread            = new Thread(() => {
                    try {
                        var fileBytes = Convert.FromBase64String(TestFileZeroCodeLength);
                        using (var ms = new MemoryStream(fileBytes))
                            using (var zip = new ZipInputStream(ms))
                            {
                                while (zip.GetNextEntry() != null)
                                {
                                }
                            }
                    }
                    catch (Exception x) {
                        threadException = x;
                    }
                });

                testThread.Start();

                if (!testThread.Join(5000))
                {
                    // Aborting threads is deprecated in .NET Core, but if we don't do this,
                    // the poor CI will hang for 2 hours upon running this test
                    ThreadEx.Abort(testThread);
                    throw new TimeoutException("Timed out waiting for GetNextEntry() to return");
                }
                else if (threadException != null)
                {
                    throw threadException;
                }
            });
        }
Ejemplo n.º 12
0
        protected virtual void PlayThread()
        {
            MediaFrame frame = null;

            while (_isworking)
            {
                lock (_queue) {
                    if (_queue.Count > 0 && !_isPaused)
                    {
                        frame = _queue.Dequeue();
                    }
                    else
                    {
                        frame = null;
                    }
                }
                if (frame != null)
                {
                    if (Speed == 1)
                    {
                        var sleep = (int)(frame.NTimetick - _syncPlayTime);

                        if (sleep < -3000)
                        {
                            lock (_queue)
                            {
                                _queue.Clear();
                            }
                        }
                        if (sleep > 0 && !_reseting)
                        {
                            Thread.Sleep(sleep);
                        }
                    }
                    else
                    {
                        var sleep = (int)(frame.NTimetick - _syncPlayTime);
                        if (sleep > 0 && !_reseting)
                        {
                            Thread.Sleep(sleep);
                        }
                    }
                    if (!_reseting)
                    {
                        _Play(frame);
                        lock (_queue) {
                            if (_curPlayTime < frame.NTimetick && !_reseting)
                            {
                                _curPlayTime = frame.NTimetick;
                            }
                        }
                    }
                    _reseting = false;
                }
                else
                {
                    ThreadEx.Sleep(10);
                }
            }
        }
Ejemplo n.º 13
0
 public static void TestIPStop()
 {
     if (ex.IsNotNull())
     {
         ex.SetAll();
         ex = null;
     }
 }
Ejemplo n.º 14
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);
                }
            }
        }
Ejemplo n.º 15
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);
        }
Ejemplo n.º 16
0
 public void Start()
 {
     if (_isWorking)
     {
         return;
     }
     _isWorking    = true;
     _analyzeThead = ThreadEx.ThreadCall(AnalyzeThead);
 }
Ejemplo n.º 17
0
 public override void Stop()
 {
     if (!_isworking)
     {
         return;
     }
     _isworking = false;
     ThreadEx.ThreadStop(_CaptureThread);
 }
Ejemplo n.º 18
0
        public void CallTimedOutMethodAsyncTest_SlowAction()
        {
            bool   isResponse = false;
            bool   isDone     = false;
            Action callBack   = new Action(() => { /*isResponse = true;*/ });

            ThreadEx.CallTimedOutMethodAsync(() => { Thread.Sleep(5000); isDone = true; }, 1000, callBack);
            Thread.Sleep(1200);
            Assert.IsFalse(isResponse && !isDone);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="checkIntervalMillisecondsTimeout">过期检查间隔,单位:毫秒,默认值为100毫秒</param>
        public ObjectCache(int checkIntervalMillisecondsTimeout = 100)
        {
            if (checkIntervalMillisecondsTimeout <= 0)
            {
                throw new ArgumentOutOfRangeException("过期检查间隔值不能小于等于0");
            }

            this._checkIntervalMillisecondsTimeout = checkIntervalMillisecondsTimeout;
            this._expirationChaeckThread           = new ThreadEx(this.ExpirationChaeckThreadMethod, "缓存项过期检查线程", true);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 停止接收
        /// </summary>
        public void Stop()
        {
            if (this._receiveDataThread == null)
            {
                return;
            }

            this._receiveDataThread.Abort();
            this._receiveDataThread = null;
        }
Ejemplo n.º 21
0
        public override void Start()
        {
            if (_isworking)
            {
                return;
            }
            _isworking = true;

            _CaptureThread = ThreadEx.ThreadCall(CaptureThread);
        }
Ejemplo n.º 22
0
 public override void Start()
 {
     if (_isworking)
     {
         return;
     }
     _isworking = true;
     ResetPosition();
     _curPlayTime = 0;
     _playThread  = ThreadEx.ThreadCall(PlayThread);
 }
Ejemplo n.º 23
0
        private void FTestAsynParallelQueue_Load(object sender, EventArgs e)
        {
            if (this.DesignMode)
            {
                return;
            }

            this._apQueue      = new AsynParallelQueue <int, string>(Pro, ProResult, 4, 10, true);
            this._retShowQueue = new AsynQueue <List <string> >(this.ProShow, "结果显示线程", true, true);
            this._createThread = new ThreadEx(this.Create, "生产线程", true);
        }
Ejemplo n.º 24
0
        private void Assets_Load(object sender, EventArgs e)
        {
            this.Text = Define.TitleBase;
            this.MaximizeBox = false;
            //this.MaximizeBox = false;

            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;

            ThreadEx threadex23 = new ThreadEx();
            threadex23.Start(new ThreadStart(threadex23.GetAssets), new EventHandler(GetAssets), this);
        }
Ejemplo n.º 25
0
 public override void Stop()
 {
     if (!_isworking)
     {
         return;
     }
     _isworking = false;
     ThreadEx.ThreadStop(_playThread);
     _queue.Clear();
     _curPlayTime = 0;
 }
Ejemplo n.º 26
0
        public virtual void Start()
        {
            if (_isworking)
            {
                return;
            }
            _isworking = true;

            OnStart();

            _threadTSStreamResolve = ThreadEx.ThreadCall(TSStreamResolveThread);
        }
Ejemplo n.º 27
0
        public void TryDequeueReferenceTest()
        {
            var queue         = new ConcurrentQueue <object>();
            var weakReference = AddObjectWeakReference(queue);

            DequeueIgnore(queue);
            ThreadEx.MemoryBarrier();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            ThreadEx.MemoryBarrier();
            Assert.IsFalse(weakReference.IsAlive);
        }
Ejemplo n.º 28
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);
        }
Ejemplo n.º 29
0
 public void Start()
 {
     if (_isworking)
     {
         return;
     }
     _isworking = true;
     ResetPosition();
     _curPlayMediaTimetick = 0;
     _playThread           = ThreadEx.ThreadCall(PlayThread);
     _yuvDraw.Start();
 }
Ejemplo n.º 30
0
    public void uploadUpgradePackage(string name)
    {
        if (!Utl.netIsActived())
        {
            EditorUtility.DisplayDialog("Alert", "The net work is not connected!", "Okay");
            return;
        }
        EditorUtility.ClearProgressBar();
        string localDir = getUpgradePackagePath(name);

        ThreadEx.exec(new System.Threading.ParameterizedThreadStart(doUploadUpgradePackage), localDir);
//		doUploadUpgradePackage (localDir);
    }
Ejemplo n.º 31
0
 public void Stop()
 {
     if (!_isworking)
     {
         return;
     }
     _isworking = false;
     _vp.Stop();
     _ap.Stop();
     ThreadEx.ThreadStop(_playThread);
     _queue = new AQueue <MediaFrame>();
     _cache = new List <MediaFrame>();
 }
Ejemplo n.º 32
0
        private TcpTransferChannel(Socket client,
                                   Action <TcpTransferChannel> clientDisconnectNotify,
                                   Action <ReceiveDatagramInfo> rev)
        {
            this._client = client;
            this._clientDisconnectNotify = clientDisconnectNotify;
            this._rev = rev;

            this._parseDataThread                  = new ThreadEx(this.ParseData, "数据解析线程", true);
            this._socketRevDataThread              = new Thread(this.RevDataThreadMethod);
            this._socketRevDataThread.Name         = "接收数据线程";
            this._socketRevDataThread.IsBackground = true;
        }
Ejemplo n.º 33
0
        public static void TestIPStart(Action<string> msg, Pub.Class.Action done)
        {
            IList<IpSetting> list = IpSettingHelper.SelectListByAll();
            if (list.Count == 0) { msg("请设置需要获取IP的网址!"); return; }
            msg("共有{0}个获取IP的网址!".FormatWith(list.Count));
            if (!ex.IsNull()) ex.SetAll();

            ex = new ThreadEx();
            list.Do((p, i) => {
                ex.QueueWorkItem(new System.Threading.WaitCallback(o => {
                    IpSetting setting = (IpSetting)o;
                    string ip = string.Empty;
                    try {
                        string data = string.Empty;
                        string name = setting.DataEncode.IfNullOrEmpty("utf-8");
                        Encoding coding = Encoding.GetEncoding(name);
                        data = GetRemoteHtmlCode(setting.IPUrl, coding);
                        if (data.Trim().IsNullEmpty()) {
                            msg("{0},error - 请检查网址{1}是否正确!".FormatWith(i + 1, setting.IPUrl));
                        } else {
                            if (setting.IPRegex.IsNullEmpty()) { //允许正则为空
                                if (data.IsNullEmpty()) {
                                    msg("{0},error - 网址{1}无法匹配IP:{2}".FormatWith(i + 1, setting.IPUrl, data));
                                } else {
                                    msg("{0},ok - 网址{1}获取的IP是:{2}".FormatWith(i + 1, setting.IPUrl, data));
                                }
                            } else {
                                string begin = setting.IPRegex.Substring(0, setting.IPRegex.IndexOf("(")).Replace("\\", "");
                                string end = setting.IPRegex.Substring(setting.IPRegex.IndexOf(")") + 1).Replace("\\", "");

                                if (begin.IsNullEmpty() || end.IsNullEmpty()) {
                                    msg("{0},error - 请检查网址{1}的正则是否正确:{2}".FormatWith(i + 1, setting.IPUrl, setting.IPRegex));
                                } else {
                                    ip = data.GetMatchingValues(setting.IPRegex, begin, end).Join(",");
                                    if (ip.IsNullEmpty()) {
                                        msg("{0},error - 网址{1}无法匹配IP:{2}".FormatWith(i + 1, setting.IPUrl, data));
                                    } else {
                                        msg("{0},ok - 网址{1}获取的IP是:{2}".FormatWith(i + 1, setting.IPUrl, ip));
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        msg("{0},error - 获取网址{1}数据出错:{2}".FormatWith(i + 1, setting.IPUrl, e.Message));
                        return;
                    }
                }), p);
            });
            ex.WaitAllComplete();
            done();
        }
Ejemplo n.º 34
0
        /// <summary>
        /// 获取外网IP地址 多线程 有一个线程取到数据后其它线程都停止
        /// </summary>
        /// <returns></returns>
        public static string GetIpFast()
        {
            string ip = string.Empty;
            ThreadEx ex = new ThreadEx();
            IList<IpSetting> list = IpSettingHelper.SelectListByAll();
            list.Do((p, i) => {
                ex.QueueWorkItem(new System.Threading.WaitCallback(o => {
                    IpSetting setting = (IpSetting)o;
                    try {
                        string data = string.Empty;
                        string name = setting.DataEncode.IfNullOrEmpty("utf-8");
                        Encoding coding = Encoding.GetEncoding(name);
                        data = GetRemoteHtmlCode(setting.IPUrl, coding);
                        if (!data.Trim().IsNullEmpty()) {
                            if (setting.IPRegex.IsNullEmpty()) { //允许正则为空
                                if (!data.IsNullEmpty()) {
                                    ip = data;
                                    ex.SetAll();
                                }
                            } else {
                                string begin = setting.IPRegex.Substring(0, setting.IPRegex.IndexOf("(")).Replace("\\", "");
                                string end = setting.IPRegex.Substring(setting.IPRegex.IndexOf(")") + 1).Replace("\\", "");

                                if (!begin.IsNullEmpty() && !end.IsNullEmpty()) {
                                    string _ip = data.GetMatchingValues(setting.IPRegex, begin, end).Join(",");
                                    if (!_ip.IsNullEmpty()) {
                                        ip = _ip;
                                        ex.SetAll();
                                    }
                                }
                            }
                        }
                    } catch { }
                }), p);
            });
            ex.WaitAllComplete();
            return ip;
        }
Ejemplo n.º 35
0
        private void Form1_Load(object sender, EventArgs e)
        {
            //String fdsa = Cookie.GetCookies(Define.Domain);
            //MessageBox.Show(fdsa);

            Data.init();

            Login login = new Login();  //新建一个NewForm窗口(NewForm是自己定义的Form)
            login.ShowDialog();         //新窗口显现

            if (Data.GetLoginResult != Define.Login_Succeed)
            {
                this.Close();
                return;
            }

            this.MaximizeBox = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            //String  dda = Des.GetMachineInfo(channel.ToString());

            CreateColumnHeader(listView_Order);
            CreateColumnHeader(listView_Completed);

            ColumnHeader BTCc1 = new ColumnHeader();
            BTCc1.Text = "比特币BTC预警";
            BTCc1.Width = 210;
            listViewBTC.Columns.AddRange(new ColumnHeader[] { BTCc1 });//将这两列加入listView1
            listViewBTC.View = View.Details;

            ColumnHeader LTCc1 = new ColumnHeader();
            LTCc1.Text = "莱特币LTC预警";
            LTCc1.Width = 210;
            listViewLTC.Columns.AddRange(new ColumnHeader[] { LTCc1 });//将这两列加入listView1
            listViewLTC.View = View.Details;

            Title = Define.TitleBase;
            this.Text = Title;

            String mac = "";
            NetworkInterface[] netWorks = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface netWork in netWorks)
            {
                mac += netWork.GetPhysicalAddress().ToString();
            }

            timer.Interval = 1000;
            timer.Enabled = true;

            timerWarnPlay.Interval = 60000;
            timerWarnPlay.Enabled = false;

            timerDepth.Interval = 1000;
            timerDepth.Enabled = true;

            timer_AccountRecord.Interval = 5000;
            timer_AccountRecord.Enabled = true;
            timer_order.Interval = 5000;
            timer_order.Enabled = true;

            timer_OrderHistory.Interval = 5000;
            timer_OrderHistory.Enabled = true;

            tabControl1.Width = 745;
            tabControl1.Height = 224;

            lab_alert.Text = "";
            lab_sell_alert.Text = "";

            cur_BTCorLTC(0);

            CSPList.Add(CSP5);
            CSPList.Add(CSP4);
            CSPList.Add(CSP3);
            CSPList.Add(CSP2);
            CSPList.Add(CSP1);

            CSNList.Add(CSN5);
            CSNList.Add(CSN4);
            CSNList.Add(CSN3);
            CSNList.Add(CSN2);
            CSNList.Add(CSN1);

            CBPList.Add(CBP1);
            CBPList.Add(CBP2);
            CBPList.Add(CBP3);
            CBPList.Add(CBP4);
            CBPList.Add(CBP5);

            CBNList.Add(CBN1);
            CBNList.Add(CBN2);
            CBNList.Add(CBN3);
            CBNList.Add(CBN4);
            CBNList.Add(CBN5);

            ThreadEx threadex = new ThreadEx();
            threadex.Start(new ThreadStart(threadex.GetCheckVersion), new EventHandler(GetCheckVersion), this);

            ThreadEx threadex2 = new ThreadEx();
            threadex2.Start(new ThreadStart(threadex2.GetUserConfig), new EventHandler(GetUserConfig), this);
        }
Ejemplo n.º 36
0
        //各网站行情信息:
        private void GetCheckVersion(Object o, EventArgs e)
        {
            if (Define.NewVersionUrl != "")
            {
                DialogResult dr;
                dr = MessageBox.Show("发现新版本,是否现在升级?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr == DialogResult.No)
                {
                    return;
                }

                ThreadEx threadex = new ThreadEx();
                threadex.Start(new ThreadStart(threadex.GetNewVersion), new EventHandler(GetNewVersion), this);
            }
        }
Ejemplo n.º 37
0
 public static void TestIPStop()
 {
     if (ex.IsNotNull()) {
         ex.SetAll();
         ex = null;
     }
 }
Ejemplo n.º 38
0
        private void OnOrder()
        {
            //timer_order.Enabled = false;

            OrderParm orderparm = new OrderParm();
            orderparm.status = "0";
            orderparm.symbol = Define.coin_cur.ToString();
            orderparm.currentPage = "1";
            orderparm.pageLength = "100";

            ThreadEx threadex = new ThreadEx();
            threadex.Start(new ParameterizedThreadStart(threadex.GetOrderHistory), (Object)orderparm, new EventHandler(GetOrder), this);
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Default copy constructor
        /// </summary>
        /// <param name="b">the object to copy from</param>
        public ThreadEx(ThreadEx b)
        {
            m_threadFunc=b.m_threadFunc;
            m_threadParameterizedFunc = b.m_threadParameterizedFunc;
            m_parameter = b.m_parameter;
	        if(m_threadFunc!=null||m_parentThreadHandle!=null)
	        {
		        m_parentThreadHandle=b.m_parentThreadHandle;
		        m_threadHandle=b.m_threadHandle;
		        m_threadPriority=b.m_threadPriority;
		        m_status=b.m_status;
		        m_exitCode=b.m_exitCode;

		        b.m_parentThreadHandle=null;
		        b.m_threadHandle=null;
		        b.m_status=ThreadStatus.TERMINATED;
		        b.m_exitCode=0;
            }
	        else
	        {
		        m_threadHandle=null;
		        m_threadPriority=b.m_threadPriority;
		        m_parentThreadHandle=null;
		        m_exitCode=0;

                m_status = ThreadStatus.TERMINATED;
	        }
        }
Ejemplo n.º 40
0
        private void timerDepth_Tick(object sender, EventArgs e)
        {
            DepthParm depthparm = new DepthParm();
            depthparm.symbol = Define.trade_symbol_cur;

            ThreadEx threadex = new ThreadEx();
            threadex.Start(new ParameterizedThreadStart(threadex.GetDepth), (Object)depthparm, new EventHandler(GetDepth), this);
        }
Ejemplo n.º 41
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();
			}
		}
Ejemplo n.º 42
0
        private void listView_BuyWait_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListView.SelectedListViewItemCollection items = listView_Order.SelectedItems;

            foreach (ListViewItem item in items)
            {
                CancelOrderParm cancelorderparm = new CancelOrderParm();
                cancelorderparm.Order_id = item.SubItems[8].Text;
                cancelorderparm.symbol = Define.trade_symbol_cur;

                ThreadEx threadex = new ThreadEx();
                threadex.Start(new ParameterizedThreadStart(threadex.GetCancelOrder), (Object)cancelorderparm, new EventHandler(GetCancelOrder), this);

                //GetTradeList(BuyOrSell.ENTRUST,ConsignState.WAIT, webBrowser3.Document, item.Index);
            }
            OnOrder();
        }
Ejemplo n.º 43
0
 /// <summary>
 /// Default Constructor
 /// </summary>
 /// <param name="fileName">name of log file</param>
 /// <param name="encodingType">encoding type</param>
 public LogWorker(string fileName, Encoding encodingType = null)
     : base(encodingType)
 {
     m_fileName = fileName;
     m_thread = new ThreadEx(this.execute, ThreadPriority.Normal);
     m_thread.Start();
 }
Ejemplo n.º 44
0
        private void Login_Load(object sender, EventArgs e)
        {
            this.Text = Define.TitleBase;
            this.MaximizeBox = false;
            //this.MaximizeBox = false;

            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;

            panel_login.Visible = true;
            panel_google.Visible = false;
            panel_qq.Visible = false;

            panel_login.Top = 0;
            panel_login.Left = 0;

            panel_google.Top = 0;
            panel_google.Left = 0;

            panel_qq.Top = 0;
            panel_qq.Left = 0;

            ThreadEx threadex = new ThreadEx();
            threadex.Start(new ThreadStart(threadex.GetCheckVersion), new EventHandler(GetCheckVersion), this);
        }
Ejemplo n.º 45
0
        private void OnGoogleCheck()
        {
            Define.GoogleCheck = txt_GoogleCheck.Text;
            if (Define.GoogleCheck != "")
            {
                GoogleCheckParm googlecheckparm = new GoogleCheckParm();
                googlecheckparm.totpCode = Define.GoogleCheck;

                ThreadEx threadex = new ThreadEx();
                threadex.Start(new ParameterizedThreadStart(threadex.GetGoogleCheck), (Object)googlecheckparm, new EventHandler(GetGoogleCheck), this);

            }
            button2.Enabled = false;
        }
Ejemplo n.º 46
0
        private void timer_OrderHistory_Tick(object sender, EventArgs e)
        {
            OrderParm orderparm = new OrderParm();
            orderparm.status = "2";
            orderparm.symbol = Define.coin_cur.ToString();
            orderparm.currentPage = "1";
            orderparm.pageLength = "100";

            ThreadEx threadex = new ThreadEx();
            threadex.Start(new ParameterizedThreadStart(threadex.GetOrderHistory), (Object)orderparm, new EventHandler(GetOrderHistory), this);
        }
Ejemplo n.º 47
0
		public void Start()
		{
			if (state!=States.Stopped) return;

			thrd = new ThreadEx(new ThreadStart(run));
			thrd.Priority=ThreadPriority.BelowNormal;
			thrd.Name="GPS_Lib";
			thrd.Start();

		}
Ejemplo n.º 48
0
		/// <summary>
		/// Stops the worker thread which monitors for changes of status
		/// of the adapter.  This must be done, if monitoring has been
		/// started, before the object is destroyed.
		/// </summary>
		public void StopStatusMonitoring()
		{
			if ( Active )
			{
				if ( mq != null )
				{
					// Close the point-to-point message queue.  This should
					// cause any waits on it to return, allowing the thread
					// to exit.
					PointToPointMsgQueue	q = mq;
					mq = null;
					q.Close();

					// Wait for the monitoring thread to exit.
					mqt.Join( 5000 );
					mqt = null;
				}
			}
		}
Ejemplo n.º 49
0
        private void OnLogin()
        {
            if (txt_Username.Text == "" || txt_password.Text == "")
            {
                MessageBox.Show(this, "用户名或密不能为空!", "登录提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }

            LoginParm loginparm = new LoginParm();
            loginparm.Username = txt_Username.Text;
            loginparm.Password = txt_password.Text;

            ThreadEx threadex = new ThreadEx();
            threadex.Start(new ParameterizedThreadStart(threadex.GetLogin), (Object)loginparm, new EventHandler(GetLogin), this);
            button1.Enabled = false;
        }
Ejemplo n.º 50
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            ThreadEx threadex = new ThreadEx();
            threadex.Start(new ThreadStart(threadex.GetUserInfo), new EventHandler(GetUserInfo), this);

            ThreadEx threadex2 = new ThreadEx();
            threadex2.Start(new ThreadStart(threadex2.GetTickerinfo), new EventHandler(GetTickerinfo), this);
        }