示例#1
0
        public Unit Startup(IActor process, ActorItem parent, Option <ICluster> cluster, int maxMailboxSize)
        {
            if (cluster.IsNone)
            {
                throw new Exception("Remote inboxes not supported when there's no cluster");
            }

            this.actor          = (Actor <S, T>)process;
            this.parent         = parent;
            this.cluster        = cluster.IfNoneUnsafe(() => null);
            this.maxMailboxSize = maxMailboxSize == -1
                ? ActorContext.System(actor.Id).Settings.GetProcessMailboxSize(actor.Id)
                : maxMailboxSize;

            userInbox = new PausableBlockingQueue <UserControlMessage>(this.maxMailboxSize);
            sysInbox  = new PausableBlockingQueue <SystemMessage>(this.maxMailboxSize);

            var obj = new ThreadObj {
                Actor = actor, Inbox = this, Parent = parent
            };

            userInbox.ReceiveAsync(obj, (state, msg) => ActorInboxCommon.UserMessageInbox(state.Actor, state.Inbox, msg, state.Parent));
            sysInbox.ReceiveAsync(obj, (state, msg) => ActorInboxCommon.SystemMessageInbox(state.Actor, state.Inbox, msg, state.Parent));

            SubscribeToSysInboxChannel();
            SubscribeToUserInboxChannel();

            return(unit);
        }
示例#2
0
    static bool tcp_check_do(string host, int port, int timeout)
    {
        Sock s = Sock.Connect(host, port, timeout, true, true);

        try
        {
            byte[] d = new byte[1];
            d[0] = (byte)'a';

            int i;
            int num = 3;

            for (i = 0; i < num; i++)
            {
                if (s.SendAll(d) == false)
                {
                    return(false);
                }

                if (i <= (num - 1))
                {
                    ThreadObj.Sleep(300);
                }
            }

            return(true);
        }
        finally
        {
            s.Disconnect();
        }
    }
示例#3
0
        static void ThreadWork(object o)
        {
            ThreadObj obj = (ThreadObj)o;

            Thread.Sleep(5000);
            obj.signalComplete.Set();
        }
示例#4
0
        public Unit Startup(IActor process, ActorItem parent, Option <ICluster> cluster, int maxMailboxSize)
        {
            if (Active)
            {
                Shutdown();
            }
            this.cluster        = cluster;
            this.parent         = parent;
            this.actor          = (Actor <S, T>)process;
            this.maxMailboxSize = maxMailboxSize == -1
                ? ActorContext.System(actor.Id).Settings.GetProcessMailboxSize(actor.Id)
                : maxMailboxSize;

            userInbox = new PausableBlockingQueue <UserControlMessage>(this.maxMailboxSize);
            sysInbox  = new PausableBlockingQueue <SystemMessage>(this.maxMailboxSize);

            var obj = new ThreadObj {
                Actor = actor, Inbox = this, Parent = parent
            };

            userInbox.ReceiveAsync(obj, (state, msg) => process.CancellationTokenSource.IsCancellationRequested ? InboxDirective.Shutdown : ActorInboxCommon.UserMessageInbox(state.Actor, state.Inbox, msg, state.Parent));
            sysInbox.ReceiveAsync(obj, (state, msg) => ActorInboxCommon.SystemMessageInbox(state.Actor, state.Inbox, msg, state.Parent));

            return(unit);
        }
示例#5
0
        // Sign for all binary files (parallel mode)
        public static void SignAllBinaryFiles()
        {
            string[] files = Directory.GetFiles(Paths.BinDirName, "*", SearchOption.AllDirectories);

            List <string> filename_list = new List <string>();

            foreach (string file in files)
            {
                if (IsFileSignable(file))
                {
                    bool isDriver = file.EndsWith(".sys", StringComparison.InvariantCultureIgnoreCase);

                    // Check whether this file is signed
                    bool isSigned = ExeSignChecker.CheckFileDigitalSignature(file);
                    if (isSigned && isDriver)
                    {
                        isSigned = ExeSignChecker.IsKernelModeSignedFile(file);
                    }

                    Con.WriteLine("The file '{0}': {1}.", file, isSigned ? "Already signed" : "Not yet signed");

                    if (isSigned == false)
                    {
                        filename_list.Add(file);
                    }
                }
            }

            Con.WriteLine("Start ProcessWorkQueue for Signing...\n");
            ThreadObj.ProcessWorkQueue(sign_thread, 40, filename_list.ToArray());
            Con.WriteLine("ProcessWorkQueue for Signing completed.\n");
        }
示例#6
0
            public WorkerQueuePrivate(ThreadProc threadProc, int numWorkerThreads, object[] tasks)
            {
                ThreadList = new List <ThreadObj>();
                int i;

                this.ThreadProc       = threadProc;
                this.NumWorkerThreads = numWorkerThreads;

                foreach (object task in tasks)
                {
                    TaskQueue.Enqueue(task);
                }

                RaisedException = null;

                for (i = 0; i < numWorkerThreads; i++)
                {
                    ThreadObj t = new ThreadObj(WorkerThread);

                    ThreadList.Add(t);
                }

                foreach (ThreadObj t in ThreadList)
                {
                    t.WaitForEnd();
                }

                if (RaisedException != null)
                {
                    throw RaisedException;
                }
            }
示例#7
0
        public Unit Startup(IActor process, ActorItem parent, Option <ICluster> cluster, int maxMailboxSize)
        {
            if (cluster.IsNone)
            {
                throw new Exception("Remote inboxes not supported when there's no cluster");
            }
            this.actor   = (Actor <S, T>)process;
            this.cluster = cluster.IfNoneUnsafe(() => null);

            this.maxMailboxSize = maxMailboxSize == -1
                ? ActorContext.System(actor.Id).Settings.GetProcessMailboxSize(actor.Id)
                : maxMailboxSize;

            this.parent = parent;

            userNotify = new PausableBlockingQueue <string>(this.maxMailboxSize);

            var obj = new ThreadObj {
                Actor = actor, Inbox = this, Parent = parent
            };

            userNotify.ReceiveAsync(obj, (state, msg) => { CheckRemoteInbox(ActorInboxCommon.ClusterUserInboxKey(state.Actor.Id), true); return(InboxDirective.Default); });

            SubscribeToSysInboxChannel();
            SubscribeToUserInboxChannel();

            this.cluster.SetValue(ActorInboxCommon.ClusterMetaDataKey(actor.Id), new ProcessMetaData(
                                      new[] { typeof(T).AssemblyQualifiedName },
                                      typeof(S).AssemblyQualifiedName,
                                      typeof(S).GetTypeInfo().ImplementedInterfaces.Map(x => x.AssemblyQualifiedName).ToArray()
                                      ));

            return(unit);
        }
示例#8
0
        void tcpAcceptedThread(object?param)
        {
            Sock s = (Sock)param !;

            ThreadObj.NoticeInited();

            this.AcceptProc(this, s, this.AcceptParam);
        }
示例#9
0
    public void GlobalLockTest()
    {
        GlobalLock k = new GlobalLock("test_lock1");

        Event   startEvent = new Event(true);
        Event   event2     = new Event(true);
        Event   event3     = new Event(true);
        RefBool fail       = new RefBool();

        var thread1 = ThreadObj.Start(x =>
        {
            try
            {
                startEvent.Wait();

                using (k.Lock())
                {
                    event2.Set();

                    if (event3.Wait(100))
                    {
                        fail.Set(true);
                    }
                }
            }
            catch
            {
                fail.Set(true);
            }
        });

        var thread2 = ThreadObj.Start(x =>
        {
            try
            {
                startEvent.Wait();

                event2.Wait();

                using (k.Lock())
                {
                    event3.Set();
                }
            }
            catch
            {
                fail.Set(true);
            }
        });

        startEvent.Set();

        Assert.True(thread1.WaitForEnd(5000));
        Assert.True(thread2.WaitForEnd(5000));

        Assert.False(fail.Value);
    }
示例#10
0
        public Listener(int port, AcceptProc acceptProc, object acceptParam, bool localOnly = false, bool getHostName = false)
        {
            this.lockObj         = new object();
            this.Port            = port;
            this.AcceptProc      = acceptProc;
            this.AcceptParam     = acceptParam;
            this.Status          = ListenerStatus.Trying;
            this.eventObj        = new Event();
            this.halt            = false;
            this.LocalOnly       = localOnly;
            this.GetHostName     = getHostName;
            this.ListenRetryTime = ListenRetryTimeDefault;

            // スレッドの作成
            ThreadObj thread = new ThreadObj(new ThreadProc(ListenerThread));

            thread.WaitForInit();
        }
示例#11
0
    // 実行開始
    public PingerTask(DnsResolver dnsClient, string targetHost, string targetHostForOk, int targetPort, int timeout, bool tcp_send_data, string defaultOptions)
    {
        //EndEvent = new Event(true);
        DnsClient            = dnsClient;
        TargetHost           = targetHost;
        TargetHostForOk      = targetHostForOk;
        TargetHostNormalized = Config.NormalizeHostNameForSort(targetHost);
        TargetPort           = targetPort;
        Timeout        = timeout;
        TcpSendData    = tcp_send_data;
        DefaultOptions = defaultOptions._NonNull();

        finished = false;
        ok       = false;
        lockObj  = new object();

        ThreadObj t = new ThreadObj(new ThreadProc(pingerThreadProc), null);

        thread = t;
    }
示例#12
0
    public static void RunStartupTest()
    {
        try
        {
            InternalTestClass c = new InternalTestClass();

            c.A = 123;
            c.B = "Hello";

            string s = c._ObjectToJson();

            if (s._InStri("Hello") == false)
            {
                throw new CoresException("s._InStri(\"Hello\") == false");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Json.RunTest Fatal Error: " + ex.ToString());
            ThreadObj.Sleep(1000);
            Environment.Exit(-1);
        }
    }
示例#13
0
        public static void SetManifest(string exe, string manifestName)
        {
            Mutex x = new Mutex(false, MutexName);

            x.WaitOne();

            try
            {
                // Manifest file name
                string filename = Path.Combine(Paths.ManifestsDir, manifestName);
                if (File.Exists(filename) == false)
                {
                    throw new FileNotFoundException(filename);
                }

                FileInfo fi = new FileInfo(exe);

                // Copy exe file to a temporary directory
                string exeTmp = IO.CreateTempFileNameByExt(".exe");
                IO.FileCopy(exe, exeTmp);

                string mtFileName = Path.Combine(Paths.MicrosoftSDKBinDir, "mt.exe");
                string mtArgs     = string.Format("-nologo -manifest \"{0}\" -outputresource:\"{1}\";1", filename, exeTmp);

                Exception ex = null;

                int i;
                // Repeated 20 times in order to avoid locking the file by the anti-virus software
                for (i = 0; i < 20; i++)
                {
                    try
                    {
                        // Execute
                        Win32BuildTool.ExecCommand(mtFileName, mtArgs, false, true);
                        ex = null;

                        break;
                    }
                    catch (Exception ex2)
                    {
                        ex = ex2;
                    }

                    ThreadObj.Sleep(Secure.Rand31i() % 50);
                }

                if (ex != null)
                {
                    throw new ApplicationException("mt.exe Manifest Processing for '" + exe + "' Failed.");
                }

                ex = null;

                // Revert to the original file
                for (i = 0; i < 20; i++)
                {
                    try
                    {
                        IO.FileCopy(exeTmp, exe);
                        ex = null;

                        break;
                    }
                    catch (Exception ex2)
                    {
                        ex = ex2;
                    }

                    ThreadObj.Sleep(Secure.Rand31i() % 50);
                }

                // Restore the date and time
                File.SetCreationTime(exe, fi.CreationTime);
                File.SetLastAccessTime(exe, fi.LastAccessTime);
                File.SetLastWriteTime(exe, fi.LastWriteTime);
            }
            finally
            {
                x.ReleaseMutex();
            }
        }
示例#14
0
        // TCP 受付完了
        void tcpAccepted(Sock s)
        {
            ThreadObj t = new ThreadObj(new ThreadProc(tcpAcceptedThread), s);

            t.WaitForInit();
        }
示例#15
0
        public static void Run()
        {
            // Using new .net 4.0 Task
            Stopwatch watch = new Stopwatch();

            watch.Start();
            System.Collections.Concurrent.ConcurrentBag <Task> tasks = new System.Collections.Concurrent.ConcurrentBag <Task>();
            Parallel.For(0, 60, i =>
            {
                Task t = Task.Factory.StartNew(() =>
                {
                    System.Threading.Thread.Sleep(5000);
                });
                tasks.Add(t);
            });
            Console.WriteLine("Waiting for task to finish");
            Task.WaitAll(tasks.ToArray());
            watch.Stop();
            Console.WriteLine("Complete(Tasks) : Time " + watch.ElapsedMilliseconds.ToString());



            //// Using Thread
            watch.Reset();
            watch.Start();
            System.Collections.Concurrent.ConcurrentBag <ManualResetEvent> tasksThreads = new System.Collections.Concurrent.ConcurrentBag <ManualResetEvent>();
            Parallel.For(0, 60, i =>
            {
                ManualResetEvent signal = new ManualResetEvent(false);
                tasksThreads.Add(signal);
                Thread t = new Thread(new ParameterizedThreadStart(ThreadWork));
                t.Start(new ThreadObj()
                {
                    signalComplete = signal, TaskItem = i
                });
            });
            Console.WriteLine("Waiting for task to finish");
            WaitHandle.WaitAll(tasksThreads.ToArray());
            watch.Stop();
            Console.WriteLine("Complete(Threads) : Time " + watch.ElapsedMilliseconds.ToString());


            //// Using ThreadPool
            watch.Reset();
            watch.Start();
            System.Collections.Concurrent.ConcurrentBag <ManualResetEvent> tasksThreadPools = new System.Collections.Concurrent.ConcurrentBag <ManualResetEvent>();
            Parallel.For(0, 60, i =>
            {
                ManualResetEvent signal = new ManualResetEvent(false);
                tasksThreadPools.Add(signal);
                ThreadObj obj = new ThreadObj()
                {
                    signalComplete = signal, TaskItem = i
                };
                ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadWork), obj);
            });
            Console.WriteLine("Waiting for task to finish");
            WaitHandle.WaitAll(tasksThreadPools.ToArray());
            watch.Stop();
            Console.WriteLine("Complete(ThreadPool) : Time " + watch.ElapsedMilliseconds.ToString());
            Console.ReadLine();
        }
示例#16
0
            public ChildProcess(string exe, string args = "", string input = "", bool throwExceptionOnExitError = false, int timeout = ThreadObj.Infinite)
            {
                this.timeout = timeout;

                Str.NormalizeString(ref args);

                ProcessStartInfo info = new ProcessStartInfo()
                {
                    FileName               = IO.InnerFilePath(exe),
                    Arguments              = args,
                    UseShellExecute        = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    RedirectStandardInput  = !Str.IsEmptyStr(input),
                };

                ThreadObj?t = null;

                using (Process p = Process.Start(info) !)
                {
                    this.proc = p;

                    if (timeout != ThreadObj.Infinite)
                    {
                        timeout_thread_event = new Event();

                        t = new ThreadObj(timeout_thread);
                    }

                    if (Str.IsEmptyStr(input) == false)
                    {
                        p.StandardInput.Write(input);
                        p.StandardInput.Flush();
                        p.StandardInput.Close();
                    }

                    stdout = p.StandardOutput.ReadToEnd();
                    stderr = p.StandardError.ReadToEnd();

                    p.WaitForExit();
                    finished = true;

                    if (timeout_thread_event != null)
                    {
                        timeout_thread_event.Set();
                    }

                    if (t != null)
                    {
                        t.WaitForEnd();
                    }

                    if (killed)
                    {
                        if (Str.IsEmptyStr(stderr))
                        {
                            stderr = $"Process run timeout ({timeout._ToString3()} msecs).";
                        }
                    }

                    exitcode = p.ExitCode;

                    if (throwExceptionOnExitError)
                    {
                        if (exitcode != 0)
                        {
                            throw new ApplicationException($"ChildProcess: '{exe}': exitcode = {exitcode}, errorstr = {stderr._OneLine()}");
                        }
                    }
                }
            }
示例#17
0
    // タスクを実行
    public PingerTask[] ExecTasks(Config config, PingerTask[] baseTaskList)
    {
        double            startTime = Time.NowHighResDouble;
        List <PingerTask> taskList  = new List <PingerTask>();
        List <PingerTask> taskList2 = new List <PingerTask>();

        int num = 0;

        if (config.TcpSendData)
        {
            Con.WriteLine("\n  starting TCP send data...\n");

            foreach (Target target in config.TargetListLastOkHost)
            {
                foreach (int port in target.Ports)
                {
                    if (port != 0)
                    {
                        PingerTask task = new PingerTask(this.DnsClient, target.HostName, config.ConvertHostnameToOkHostname(target.HostName), port, config.Timeout, true, config.DefaultOptions);

                        taskList2.Add(task);
                    }
                }
            }
            foreach (Target target in config.TargetListLastNgHost)
            {
                foreach (int port in target.Ports)
                {
                    if (port != 0)
                    {
                        PingerTask task = new PingerTask(this.DnsClient, target.HostName, config.ConvertHostnameToOkHostname(target.HostName), port, config.Timeout, true, config.DefaultOptions);

                        taskList2.Add(task);
                    }
                }
            }
            foreach (PingerTask task in taskList2)
            {
                if (task != null)
                {
                    task.WaitForEnd();
                }
            }
            Con.WriteLine("\n  TCP send data ended.\n");
        }

        // 各タスクの開始
        foreach (Target target in config.TargetListLastOkHost)
        {
            foreach (int port in target.Ports)
            {
                PingerTask task = null !;
                bool       ok   = false;
                if (baseTaskList != null)
                {
                    if (baseTaskList[num].Ok)
                    {
                        if (config.TcpSendData == false || port == 0)
                        {
                            // すでに前回で Ok が出ている
                            ok = true;
                        }
                    }
                }

                if (ok == false)
                {
                    task = new PingerTask(this.DnsClient, target.HostName, config.ConvertHostnameToOkHostname(target.HostName), port, config.Timeout, config.TcpSendData, config.DefaultOptions);
                }

                taskList.Add(task);

                num++;
            }
        }
        ThreadObj.Sleep(1000);
        foreach (Target target in config.TargetListLastNgHost)
        {
            foreach (int port in target.Ports)
            {
                PingerTask task = null !;
                bool       ok   = false;
                if (baseTaskList != null)
                {
                    if (baseTaskList[num].Ok)
                    {
                        if (config.TcpSendData == false || port == 0)
                        {
                            // すでに前回で Ok が出ている
                            ok = true;
                        }
                    }
                }

                if (ok == false)
                {
                    task = new PingerTask(this.DnsClient, target.HostName, config.ConvertHostnameToOkHostname(target.HostName), port, config.Timeout, config.TcpSendData, config.DefaultOptions);
                }

                taskList.Add(task);

                num++;
            }
        }

        // タスクの完了の待機
        foreach (PingerTask task in taskList)
        {
            if (task != null)
            {
                task.WaitForEnd();

                if (config.TcpSendData)
                {
                    if (task.TargetPort != 0)
                    {
                        task.TcpNg = !task.Ok;
                    }
                }

                if (task.Ok)
                {
                    CurrentOkHostList.Add(task.TargetHost);
                }
            }
        }

        double endTime = Time.NowHighResDouble;

        return(taskList.ToArray());
    }
示例#18
0
        // スレッド
        public void ListenerThread(object?param)
        {
            Sock?new_sock;
            Sock s;
            int  num_failed;

            this.thread = ThreadObj.GetCurrentThreadObj() !;

            this.Status = ListenerStatus.Trying;

            ThreadObj.NoticeInited();

            while (true)
            {
                bool firstFailed = true;
                this.Status = ListenerStatus.Trying;

                // Listen を試みる
                while (true)
                {
                    if (this.halt)
                    {
                        return;
                    }

                    try
                    {
                        s = Sock.Listen(this.Port, this.LocalOnly);

                        this.Sock = s;

                        break;
                    }
                    catch
                    {
                        if (firstFailed)
                        {
                            firstFailed = false;
                        }

                        this.eventObj.Wait(this.ListenRetryTime);

                        if (this.halt)
                        {
                            return;
                        }
                    }
                }

                this.Status = ListenerStatus.Listening;

                if (this.halt)
                {
                    this.Sock.Disconnect();
                    break;
                }

                num_failed = 0;

                // Accept ループ
                while (true)
                {
                    // Accept する
                    new_sock = this.Sock.Accept(this.GetHostName);
                    if (new_sock != null)
                    {
                        // 成功
                        tcpAccepted(new_sock);
                    }
                    else
                    {
                        // 失敗
                        if (this.halt == false)
                        {
                            if ((++num_failed) <= 5)
                            {
                                continue;
                            }
                        }

                        this.Sock.Disconnect();
                        break;
                    }
                }

                if (this.halt)
                {
                    return;
                }
            }
        }
示例#19
0
        private void MainThread()
        {
            Threads = new Dictionary <Int32, ThreadObj>();
            //eventLog1.BeginInit();
            STKTVMain.TVMain TvMain;
            int RequestInterval = 60000;

            DateTime TGKSendTime;
            DateTime AnalizerTime;

            AnalizerTime = DateTime.Now;
            TGKSendTime  = DateTime.Now;
            TGKSendTime  = TGKSendTime.AddMinutes(2);
            AnalizerTime = AnalizerTime.AddMinutes(10);

            DataRow dr;
            int     ModemCount = 0;
            bool    bLogged    = false;

            do
            {
                bLogged = false;
                TvMain  = new STKTVMain.TVMain();
                do
                {
                    // случилось команда на выход из сервиса
                    if (pStopServiceEvent.WaitOne(1, false))
                    {
                        try
                        {
                            InfoReport("Exiting working thread...");
                            StopDeviceThreads();
                            pStopApprovedEvent.Set();
                            return;
                        }
                        catch (Exception Ex)
                        {
                            ErrorReport("Exiting working thread error: " + Ex.Message);
                            return;
                        }
                    }



                    // пытаемся соединиться с базой данных
                    try
                    {
                        //InfoReport("Try DB login.");
                        if (TvMain.Init() == true)
                        {
                            bLogged         = true;
                            RequestInterval = TvMain.RequestInterval;
                        }
                        else
                        {
                            //pRefService.WarningReport("Unable to login, check credentials");
                            WarningReport("Unable to login, check credentials");
                            InfoReport(TvMain.GetEnvInfo());
                        }
                    }
                    catch (Exception Ex)
                    {
                        //pRefService.ErrorReport("Login failed, try again... " + Ex.Message);
                        ErrorReport("Login failed, try again... " + Ex.Message);
                        InfoReport(TvMain.GetEnvInfo());
                    }
                } while (!pStopServiceEvent.WaitOne(1000, false) && !bLogged);
                //pRefService.InfoReport("DB Initialization OK");
                //InfoReport("DB Initialization OK");



                // соединение прошло успешно
                if (bLogged)
                {
                    try
                    {
                        ModemCount = TvMain.GetStationModemCount();
                        System.Data.DataTable oRS;
                        ThreadObj             throbj = null;

                        oRS = null;
                        oRS = TvMain.GetDBDevicePlanListModem();


                        if (oRS != null)
                        {
                            if (oRS.Rows.Count > 0)
                            {
                                InfoReport("Checking " + oRS.Rows.Count + " active plan(s) at " + DateTime.Now.ToString());
                                for (int i = 0; i < oRS.Rows.Count && i < 10 && ActiveThreadsCount() <= ModemCount + 1; i++)
                                {
                                    try
                                    {
                                        dr    = oRS.Rows[i];
                                        id_bd = Convert.ToInt32(dr["id_bd"].ToString());
                                        if (!Threads.ContainsKey(id_bd))
                                        {
                                            // создаем и стартуем новый процесс для опроса устройства
                                            throbj       = new ThreadObj();
                                            throbj.DevID = id_bd;
                                            Process p = new Process();
                                            String  FileName;
                                            FileName = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + "\\STKDeviceThread.exe";
                                            String DirName = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location);
                                            p.StartInfo.FileName         = FileName;
                                            p.StartInfo.Arguments        = "-D " + id_bd.ToString();
                                            p.StartInfo.WorkingDirectory = DirName;
                                            throbj.Process = p;
                                            Threads.Add(id_bd, throbj);
                                            throbj.Process.Start();
                                        }
                                        else
                                        {
                                            if (Threads[id_bd].Process.HasExited == true || Threads[id_bd].Process.StartTime.AddMinutes(15) <= DateTime.Now)
                                            {
                                                // инициализируем процесс еще раз
                                                // сначала убиваем процесс
                                                try
                                                {
                                                    Threads[id_bd].Process.Kill();
                                                }
                                                catch
                                                {
                                                }
                                                throbj       = new ThreadObj();
                                                throbj.DevID = id_bd;
                                                Process p = new Process();
                                                String  FileName;
                                                FileName = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + "\\STKDeviceThread.exe";
                                                String DirName = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location);

                                                p.StartInfo.FileName         = FileName;
                                                p.StartInfo.Arguments        = "-D " + id_bd.ToString();
                                                p.StartInfo.WorkingDirectory = DirName;
                                                throbj.Process = p;
                                                Threads[id_bd] = throbj;
                                                throbj.Process.Start();
                                            }
                                        }
                                    }
                                    catch (Exception Ex)
                                    {
                                        ErrorReport("Thread " + id_bd.ToString() + " error:" + Ex.Message);
                                    }
                                    Thread.Sleep(8000);  // wait for modem pull locking
                                }
                            } // зершение цикла по активным устройствам

                            oRS    = null;
                            throbj = null;
                        }
                    }
                    catch
                    { }


                    //if (true)  //Analizer flag
                    //{
                    //    if (AnalizerTime <= DateTime.Now)
                    //    {
                    //        try{
                    //            System.Diagnostics.Process.Start(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + "\\NCAnalizer.exe");
                    //            AnalizerTime = DateTime.Now.AddMinutes(13);
                    //        }catch {
                    //        }
                    //    }
                    //}

                    if (TvMain.SendToTGK)
                    {
                        if (TGKSendTime <= DateTime.Now)
                        {
                            try
                            {
                                System.Diagnostics.Process.Start(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + "\\TGKSender.exe");
                                TGKSendTime = DateTime.Now.AddHours(6);
                            }
                            catch
                            {
                            }
                        }
                    }
                    try
                    {
                        TvMain.DeviceClose();
                        TvMain.CloseDBConnection();
                    }
                    catch { }
                }
                TvMain = null;
            } while (!pStopServiceEvent.WaitOne(RequestInterval, false));

            try
            {
                InfoReport("Closing STKServiceModem...");
                StopDeviceThreads();
                Threads.Clear();
                Threads = null;
                dr      = null;
                // base.OnStop();
                //eventLog1.Dispose();
                return;
            }
            catch (Exception Ex)
            {
                ErrorReport("Closing STKServiceModem error:" + Ex.Message);
            }
        }
示例#20
0
    public void SingleInstanceTest()
    {
        Event   startEvent = new Event(true);
        RefBool fail       = new RefBool();
        Event   event2     = new Event(true);
        Event   event3     = new Event(true);
        Event   event4     = new Event(true);
        Event   event5     = new Event(true);
        Event   event6     = new Event(true);

        var thread1 = ThreadObj.Start(x =>
        {
            try
            {
                startEvent.Wait();

                using (var si2 = new SingleInstance("si_test"))
                {
                    event2.Set();

                    event3.Wait();
                }

                event4.Set();

                event5.Wait();

                var si = SingleInstance.TryGet("si_test");
                if (si != null)
                {
                    fail.Set(true);
                }

                event6.Set();
            }
            catch
            {
                fail.Set(true);
            }
        });

        var thread2 = ThreadObj.Start(x =>
        {
            try
            {
                startEvent.Wait();

                event2.Wait();

                var si = SingleInstance.TryGet("si_test");
                if (si != null)
                {
                    fail.Set(true);
                }

                event3.Set();

                event4.Wait();

                si = SingleInstance.TryGet("si_test");
                if (si == null)
                {
                    fail.Set(true);
                }

                event5.Set();

                event6.Wait();

                si._DisposeSafe();
            }
            catch
            {
                fail.Set(true);
            }
        });

        startEvent.Set();

        Assert.True(thread1.WaitForEnd(5000));
        Assert.True(thread2.WaitForEnd(5000));

        Assert.False(fail.Value);
    }
示例#21
0
        static void Net_Test11_AcceptLoop()
        {
            if (test11_flag == false)
            {
                test11_flag = true;

                new ThreadObj(param =>
                {
                    ThreadObj.Current.Thread.Priority = System.Threading.ThreadPriority.Highest;
                    int last = 0;
                    while (true)
                    {
                        int value = Environment.TickCount;
                        int span  = value - last;
                        last      = value;
                        Console.WriteLine("tick: " + span);
                        ThreadObj.Sleep(100);
                    }
                });
            }

            using (var listener = LocalNet.CreateListener(new TcpListenParam(
                                                              async(listener2, sock) =>
            {
                while (true)
                {
                    var stream = sock.GetStream();
                    StreamReader r = new StreamReader(stream);

                    while (true)
                    {
                        string?line = await r.ReadLineAsync();

                        if (line._IsEmpty())
                        {
                            break;
                        }
                    }
                    int segmentSize = 400;
                    int numSegments = 1000;
                    int totalSize = segmentSize * numSegments;

                    string ret =
                        $@"HTTP/1.1 200 OK
Content-Length: {totalSize}

";

                    await stream.WriteAsync(ret._GetBytes_Ascii());

                    byte[] buf = Util.Rand(numSegments);
                    for (int i = 0; i < numSegments; i++)
                    {
                        await stream.WriteAsync(buf);
                    }
                }
            },
                                                              null,
                                                              80)))
            {
                Con.ReadLine(" > ");
            }
        }
示例#22
0
        public static void Service()
        {
            Thread.CurrentThread.IsBackground = false;
            while (true)
            {
                Console.WriteLine("Waiting for connections...");
                Socket soc = listener.AcceptSocket();
                //soc.SetSocketOption(SocketOptionLevel.Socket,
                //        SocketOptionName.ReceiveTimeout,10000);

                Stream       s  = new NetworkStream(soc);
                StreamReader sr = new StreamReader(s);
                StreamWriter sw = new StreamWriter(s);

                Console.WriteLine($"{Environment.NewLine}Connected: {soc.RemoteEndPoint}");

                try
                {
                    sw.AutoFlush = true; // enable automatic flushing


                    //thread to read from server
                    ThreadObj obj = new ThreadObj();
                    obj.RemoteName = soc.RemoteEndPoint.ToString();
                    obj.SR         = sr;
                    obj.SW         = sw;
                    //ParameterizedThreadStart ts = ReadClient;
                    //Thread t = new Thread(ts);
                    //t.Start(obj);

                    Task t = Task.Run(() => ReadClient(obj));

                    string sTextToSend = string.Empty;

                    while (true)
                    {
                        Console.Write($"{Environment.UserName} -> {soc.RemoteEndPoint.ToString()}: ");
                        sTextToSend =
                            Console.ReadLine();
                        if (sTextToSend == "killclient")
                        {
                            obj.KillSwitch = true;
                            Console.WriteLine($"KillClient issued");
                            sw.WriteLine($"{sTextToSend.ToUpper()}");
                            break;
                        }
                        else if (sTextToSend == "")
                        {
                            //wait 1 second
                            Thread.Sleep(1000);
                            if (t.IsFaulted)
                            {
                                break;
                            }
                            //if (t.ThreadState == ThreadState.Stopped) break;
                        }
                        sw.WriteLine($"{Environment.UserName} says: {sTextToSend}");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                finally
                {
                    sw.Close();
                    sr.Close();
                    s.Close();
                }

                Console.WriteLine("Disconnected: {0}",
                                  soc.RemoteEndPoint);
                soc.Close();
            }
        }
示例#23
0
        static void Net_Test12_AcceptLoop2(int port = 80)
        {
            new ThreadObj(param =>
            {
                ThreadObj.Current.Thread.Priority = System.Threading.ThreadPriority.Highest;
                int last = 0;
                while (true)
                {
                    int value = Environment.TickCount;
                    int span  = value - last;
                    last      = value;
                    long mem  = mem = GC.GetTotalMemory(false);
                    try
                    {
                        Console.WriteLine("tick: " + span + "   mem = " + mem / 1024 / 1024 + "    sock = " + LocalNet.GetOpenedSockCount());
                    }
                    catch { }
                    ThreadObj.Sleep(100);
                }
            });

            if (true)
            {
                NetTcpListener listener = LocalNet.CreateListener(new TcpListenParam(
                                                                      async(listener2, sock) =>
                {
                    while (true)
                    {
                        var stream     = sock.GetStream();
                        StreamReader r = new StreamReader(stream);

                        while (true)
                        {
                            string?line = await r.ReadLineAsync();

                            if (line._IsEmpty())
                            {
                                break;
                            }
                        }
                        int segmentSize = 400;
                        int numSegments = 1000;
                        int totalSize   = segmentSize * numSegments;

                        string ret =
                            $@"HTTP/1.1 200 OK
Content-Length: {totalSize}

";

                        await stream.WriteAsync(ret._GetBytes_Ascii());

                        byte[] buf = Util.Rand(numSegments);
                        for (int i = 0; i < numSegments; i++)
                        {
                            await stream.WriteAsync(buf);
                        }
                    }
                },
                                                                      null,
                                                                      port));

                listener.HideAcceptProcError = true;

                ThreadObj.Sleep(-1);
            }
        }
示例#24
0
        private void MainThread()
        {
            Threads = new Dictionary<Int32, ThreadObj>();
            eventLog1.BeginInit();
            STKTVMain.TVMain TvMain;
            int RequestInterval = 60000;

            DateTime TGKSendTime;
            DateTime AnalizerTime;
            AnalizerTime = DateTime.Now;
            TGKSendTime = DateTime.Now;
            TGKSendTime = TGKSendTime.AddMinutes(2);
            AnalizerTime = AnalizerTime.AddMinutes(10);

            DataRow dr;
            int ModemCount = 0;
            bool bLogged = false;
            do
            {
                bLogged = false;
                TvMain = new STKTVMain.TVMain();
                do
                {
                    // случилось команда на выход из сервиса
                    if (pStopServiceEvent.WaitOne(1, false))
                    {
                        try
                        {

                            InfoReport("Exiting working thread...");
                            StopDeviceThreads();
                            pStopApprovedEvent.Set();
                            return;
                        }
                        catch (Exception Ex)
                        {
                            ErrorReport("Exiting working thread error: " + Ex.Message);
                            return;
                        }
                    }



                    // пытаемся соединиться с базой данных
                    try
                    {

                        //InfoReport("Try DB login.");
                        if (TvMain.Init() == true)
                        {
                            bLogged = true;
                            RequestInterval = TvMain.RequestInterval;
                        }
                        else
                        {
                            //pRefService.WarningReport("Unable to login, check credentials");
                            WarningReport("Unable to login, check credentials");
                            InfoReport(TvMain.GetEnvInfo());
                        }
                    }
                    catch (Exception Ex)
                    {
                        //pRefService.ErrorReport("Login failed, try again... " + Ex.Message);
                        ErrorReport("Login failed, try again... " + Ex.Message);
                        InfoReport(TvMain.GetEnvInfo());
                    }
                } while (!pStopServiceEvent.WaitOne(1000, false) && !bLogged);
                //pRefService.InfoReport("DB Initialization OK");
                //InfoReport("DB Initialization OK");



                // соединение прошло успешно
                if (bLogged)
                {
                    try
                    {

                        ModemCount = TvMain.GetStationModemCount();
                        System.Data.DataTable oRS;
                        ThreadObj throbj = null;

                        oRS = null;
                        oRS = TvMain.GetDBDevicePlanListModem();


                        if (oRS != null)
                        {

                            if (oRS.Rows.Count > 0)
                            {
                                InfoReport("Checking " + oRS.Rows.Count + " active plan(s) at " + DateTime.Now.ToString());
                                for (int i = 0; i < oRS.Rows.Count && i < 10 && ActiveThreadsCount() < ModemCount;  i++)
                                {

                                    try
                                    {
                                        dr = oRS.Rows[i];
                                        id_bd = Convert.ToInt32(dr["id_bd"].ToString());
                                        if (!Threads.ContainsKey(id_bd))
                                        {

                                            // создаем и стартуем новый процесс для опроса устройства
                                            throbj = new ThreadObj();
                                            throbj.DevID = id_bd;
                                            Process p = new Process();
                                            String FileName;
                                            FileName = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + "\\STKDeviceThread.exe";
                                            String DirName = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location);
                                            p.StartInfo.FileName = FileName;
                                            p.StartInfo.Arguments = "-D " + id_bd.ToString();
                                            p.StartInfo.WorkingDirectory = DirName;
                                            throbj.Process = p;
                                            Threads.Add(id_bd, throbj);
                                            throbj.Process.Start();


                                        }
                                        else
                                        {
                                            if (Threads[id_bd].Process.HasExited == true || Threads[id_bd].Process.StartTime.AddMinutes(30) <= DateTime.Now)
                                            {
                                                // инициализируем процесс еще раз
                                                // сначала убиваем процесс
                                                try
                                                {
                                                    Threads[id_bd].Process.Kill();
                                                }catch{

                                                }
                                                throbj = new ThreadObj();
                                                throbj.DevID = id_bd;
                                                Process p = new Process();
                                                String FileName;
                                                FileName = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + "\\STKDeviceThread.exe";
                                                String DirName = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location);

                                                p.StartInfo.FileName = FileName;
                                                p.StartInfo.Arguments = "-D " + id_bd.ToString();
                                                p.StartInfo.WorkingDirectory = DirName;
                                                throbj.Process = p;
                                                Threads[id_bd] = throbj;
                                                throbj.Process.Start();

                                            }
                                          
                                           
                                        }

                                    }
                                    catch (Exception Ex)
                                    {
                                        ErrorReport("Thread " + id_bd.ToString() + " error:" + Ex.Message);
                                    }
                                    Thread.Sleep(8000);  // wait for modem pull locking
                                }
                            } // зершение цикла по активным устройствам 

                            oRS = null;
                            throbj = null;

                        }
                    }
                    catch 
                    { }


                    //if (true)  //Analizer flag
                    //{
                    //    if (AnalizerTime <= DateTime.Now)
                    //    {
                    //        try{
                    //            System.Diagnostics.Process.Start(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + "\\NCAnalizer.exe");
                    //            AnalizerTime = DateTime.Now.AddMinutes(13);
                    //        }catch {
                    //        }
                    //    }
                    //}

                    if (TvMain.SendToTGK)
                    {

                        if (TGKSendTime <= DateTime.Now)
                        {
                            try{
                                System.Diagnostics.Process.Start(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + "\\TGKSender.exe");
                                TGKSendTime = DateTime.Now.AddHours(6);
                            }
                            catch{
                            }
                        }
                    }
                    try
                    {
                        TvMain.DeviceClose();
                        TvMain.CloseDBConnection();
                    }
                    catch { }
                }
                TvMain = null;

               
            } while (!pStopServiceEvent.WaitOne(RequestInterval, false));

            try
            {
                InfoReport("Closing STKServiceModem...");
                StopDeviceThreads();
                Threads.Clear();
                Threads = null;
                dr = null;
                base.OnStop();
                eventLog1.Dispose();
                return;
            }
            catch (Exception Ex)
            {
                ErrorReport("Closing STKServiceModem error:" + Ex.Message);
            }
            
            
        }
示例#25
0
    public static unsafe void Poll(IntPtr[] reads, IntPtr[] writes, int timeout)
    {
        if (timeout == 0)
        {
            return;
        }

        PollEvent[] p;
        int         num, n, num_read_total, num_write_total;

        num_read_total = num_write_total = 0;
        foreach (IntPtr fd in reads)
        {
            if ((int)fd != -1)
            {
                num_read_total++;
            }
        }
        foreach (IntPtr fd in writes)
        {
            if ((int)fd != -1)
            {
                num_write_total++;
            }
        }

        num = num_read_total + num_write_total;

        p = new PollEvent[num];

        n = 0;

        foreach (IntPtr fd in reads)
        {
            if ((int)fd != -1)
            {
                p[n].FileDescriptor = (int)fd;
                p[n].Events         = PollEvents.POLLIN | PollEvents.POLLPRI | PollEvents.POLLERR | PollEvents.POLLHUP;
                n++;
            }
        }

        foreach (IntPtr fd in writes)
        {
            if ((int)fd != -1)
            {
                p[n].FileDescriptor = (int)fd;
                p[n].Events         = PollEvents.POLLIN | PollEvents.POLLPRI | PollEvents.POLLERR | PollEvents.POLLHUP | PollEvents.POLLOUT;
                n++;
            }
        }

        if (num == 0)
        {
            ThreadObj.Sleep(timeout);
        }
        else
        {
            //Dbg.WriteLine("Poll Begin.");

            int ret = Poll(p, timeout);

            //Dbg.WriteLine($"Poll end: ret = {ret}, reads = {reads.Length}, writes = {writes.Length}, pfds = {p.Length}");

            //for (int i = 0; i < reads.Length; i++) Dbg.WriteLine($"reads[{i}] = {reads[i]}");
            //for (int i = 0; i < writes.Length; i++) Dbg.WriteLine($"writes[{i}] = {writes[i]}");
        }
    }
示例#26
0
        public static void SetManifest(string exe, string manifestName)
        {
            Mutex x = new Mutex(false, MutexName);

            x.WaitOne();

            try
            {
                // Manifest file name
                string filename = Path.Combine(Paths.ManifestsDir, manifestName);
                if (File.Exists(filename) == false)
                {
                    throw new FileNotFoundException(filename);
                }

                FileInfo fi = new FileInfo(exe);

                // Copy exe file to a temporary directory
                string exeTmp = IO.CreateTempFileNameByExt(".exe");
                IO.FileCopy(exe, exeTmp);

                // Create a batch file
                string       batFileName = Path.Combine(Paths.TmpDirName, "exec_mt.cmd");
                StreamWriter bat         = new StreamWriter(batFileName, false, Str.ShiftJisEncoding);
                bat.WriteLine("call \"{0}\"", Paths.VisualStudioVCBatchFileName);
                bat.WriteLine("echo on");
                bat.WriteLine("mt.exe -manifest \"{0}\" -outputresource:\"{1}\";1", filename, exeTmp);
                bat.WriteLine("EXIT /B %ERRORLEVEL%");
                bat.Close();

                Exception ex = null;

                int i;
                // Repeated 20 times in order to avoid locking the file by the anti-virus software
                for (i = 0; i < 20; i++)
                {
                    try
                    {
                        // Execute
                        Win32BuildUtil.ExecCommand(Paths.CmdFileName, string.Format("/C \"{0}\"", batFileName), true);
                        ex = null;

                        break;
                    }
                    catch (Exception ex2)
                    {
                        ex = ex2;
                    }

                    ThreadObj.Sleep(Secure.Rand31i() % 50);
                }

                if (ex != null)
                {
                    throw new ApplicationException("mt.exe Manifest Processing for '" + exe + "' Failed.");
                }

                // Revert to the original file
                IO.FileCopy(exeTmp, exe);

                // Restore the date and time
                File.SetCreationTime(exe, fi.CreationTime);
                File.SetLastAccessTime(exe, fi.LastAccessTime);
                File.SetLastWriteTime(exe, fi.LastWriteTime);
            }
            finally
            {
                x.ReleaseMutex();
            }
        }
示例#27
0
        private void MainThread()
        {
            Threads = new Dictionary <Int32, ThreadObj>();
            eventLog1.BeginInit();
            STKTVMain.TVMain TvMain;
            DataRow          dr;
            int RequestInterval = 60000;

            bool bLogged = false;

            do
            {
                bLogged = false;
                TvMain  = new STKTVMain.TVMain();
                do
                {
                    // случилось команда на выход из сервиса
                    if (pStopServiceEvent.WaitOne(1, false))
                    {
                        try
                        {
                            InfoReport("Exiting working thread...");
                            StopDeviceThreads();
                            pStopApprovedEvent.Set();
                            return;
                        }
                        catch (Exception Ex)
                        {
                            ErrorReport("Exiting working thread error: " + Ex.Message);
                            return;
                        }
                    }



                    // пытаемся соединиться с базой данных
                    try
                    {
                        InfoReport("Try DB login.");
                        if (TvMain.Init(true) == true)
                        {
                            bLogged         = true;
                            RequestInterval = TvMain.RequestInterval;
                        }
                        else
                        {
                            //pRefService.WarningReport("Unable to login, check credentials");
                            WarningReport("Unable to login, check credentials");
                            InfoReport(TvMain.GetEnvInfo());
                        }
                    }
                    catch (Exception Ex)
                    {
                        //pRefService.ErrorReport("Login failed, try again... " + Ex.Message);
                        ErrorReport("Login failed, try again... " + Ex.Message);
                        InfoReport(TvMain.GetEnvInfo());
                    }
                } while (!pStopServiceEvent.WaitOne(1000, false) && !bLogged);
                //pRefService.InfoReport("DB Initialization OK");
                InfoReport("DB Initialization OK");


                // соединение прошло успешно
                if (bLogged)
                {
                    System.Data.DataTable oRS;
                    ThreadObj             throbj = null;


                    oRS = null;
                    oRS = TvMain.GetDBDevicePlanList();


                    if (oRS != null)
                    {
                        if (oRS.Rows.Count > 0)
                        {
                            InfoReport("Checking " + oRS.Rows.Count + " active plan(s) at " + DateTime.Now.ToString());
                            for (int i = 0; i < oRS.Rows.Count; i++)
                            {
                                try
                                {
                                    dr    = oRS.Rows[i];
                                    id_bd = Convert.ToInt32(dr["id_bd"].ToString());
                                    if (!Threads.ContainsKey(id_bd))
                                    {
                                        // создаем и стартуем новый процесс для опроса устройства
                                        throbj       = new ThreadObj();
                                        throbj.DevID = id_bd;
                                        Process p = new Process();
                                        String  FileName;
                                        FileName = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + "\\STKDeviceThread.exe";
                                        String DirName = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location);
                                        p.StartInfo.FileName         = FileName;
                                        p.StartInfo.Arguments        = "-D " + id_bd.ToString();
                                        p.StartInfo.WorkingDirectory = DirName;
                                        throbj.Process = p;
                                        Threads.Add(id_bd, throbj);
                                        throbj.Process.Start();
                                    }
                                    else
                                    {
                                        if (Threads[id_bd].Process.HasExited == true)
                                        {
                                            // инициализируем процесс еще раз
                                            Threads[id_bd].Process.Close();
                                            throbj       = new ThreadObj();
                                            throbj.DevID = id_bd;
                                            Process p = new Process();
                                            String  FileName;
                                            FileName = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + "\\STKDeviceThread.exe";
                                            String DirName = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location);

                                            p.StartInfo.FileName         = FileName;
                                            p.StartInfo.Arguments        = "-D " + id_bd.ToString();
                                            p.StartInfo.WorkingDirectory = DirName;
                                            throbj.Process = p;
                                            Threads[id_bd] = throbj;
                                            throbj.Process.Start();
                                        }
                                    }
                                }
                                catch (Exception Ex)
                                {
                                    ErrorReport("Thread " + id_bd.ToString() + " error:" + Ex.Message);
                                }
                            }
                        } // зершение цикла по активным устройствам

                        oRS    = null;
                        throbj = null;
                    }
                }

                TvMain.EndInit(true);
                //TvMain.CloseDBConnection();
                TvMain = null;
            } while (!pStopServiceEvent.WaitOne(RequestInterval, false));

            try
            {
                InfoReport("Closing STKService...");
                StopDeviceThreads();
                Threads.Clear();
                Threads = null;
                dr      = null;
                //base.OnStop();
                eventLog1.Dispose();
                return;
            }
            catch (Exception Ex)
            {
                ErrorReport("Closing STKService error:" + Ex.Message);
            }
        }
示例#28
0
        public string registry(string codes, RecvRealtimeData rrd)
        {
            string bingo = "";

            string[] arrRegistryCode = { };

            if (codes.ToLower() == "all" ||
                codes == null ||
                codes == "")
            {
                arrRegistryCode = new string[this.dcCodeIdxThObj.Count]; this.dcCodeIdxThObj.Keys.CopyTo(arrRegistryCode, 0);
            }
            else
            {
                arrRegistryCode = codes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            }

            lock (lockRsrc)
            {
                createDataList(rrd);

                foreach (var item in arrRegistryCode)
                {
                    //...
                    if (!this.dcCodeIdxThObj.ContainsKey(item))
                    {
                        ThreadObj to = this.ltThObj[idxThObjForNewRegistry];
                        if (to.GetType().Equals(typeof(ThreadGetDataFromTradeX)))
                        {
                            this.dcCodeIdxThObj.Add(item, idxThObjForNewRegistry);
                            ((ThreadGetDataFromTradeX)to).addObj(item);

                            idxThObjForNewRegistry++;
                            if (idxThObjForNewRegistry >= this.ltThObj.Count)
                            {
                                idxThObjForNewRegistry = 0;
                            }
                        }
                    }

                    if (this.dcCodeIdxThObj.ContainsKey(item))
                    {
                        if (!this.dcCodeRRD.ContainsKey(item))
                        {
                            this.dcCodeRRD.Add(item, new List <RecvRealtimeData>());
                        }
                        this.dcCodeRRD[item].Add(rrd);

                        if (!this.dcRRDReferencedCount.ContainsKey(rrd))
                        {
                            this.dcRRDReferencedCount.Add(rrd, 1);
                        }
                        else
                        {
                            this.dcRRDReferencedCount[rrd]++;
                        }

                        bingo += (item + ",");
                    }

                    if (this.dcCodeLastRd.ContainsKey(item))
                    {
                        pushData(rrd, this.dcCodeLastRd[item]);
                    }
                }
            }

            return(bingo);
        }
        public static void jsonrpc_client_server_both_test()
        {
            //jsonrpc_server_invoke_test().Wait();return;

            // start server
            HttpServerOptions http_cfg = new HttpServerOptions()
            {
                DebugKestrelToConsole = false,
            };
            JsonRpcServerConfig rpc_cfg = new JsonRpcServerConfig()
            {
            };

            using (RpcServerApiTest h = new RpcServerApiTest())
                using (var s = JsonRpcHttpServerBuilder.StartServer(http_cfg, rpc_cfg, h))
                {
                    Ref <bool> client_stop_flag = new Ref <bool>();

                    // start client
                    ThreadObj client_thread = ThreadObj.Start(param =>
                    {
                        //Kernel.SleepThread(-1);

                        //using ()
                        {
                            //c.AddHeader("X-1", "Hello");

                            rpctmp1 t = new rpctmp1();
                            t.a       = new rpc_t()
                            {
                                Int1 = 2,
                                Str1 = "Neko",
                            };

                            //JsonRpcResponse<object> ret = c.CallOne<object>("Test1", t).Result;
                            //JsonRpcResponse<object> ret = c.CallOne<object>("Test2", t).Result;

                            Benchmark b = new Benchmark("rpccall");

                            JsonRpcHttpClient <rpc_server_api_interface_test> c = new JsonRpcHttpClient <rpc_server_api_interface_test>("http://127.0.0.1:88/rpc");
                            var threads = ThreadObj.StartMany(256, par =>
                            {
                                while (client_stop_flag.Value == false)
                                {
                                    //c.Call.Divide(8, 2).Wait();
                                    TMP1 a = new TMP1()
                                    {
                                        a = 4, b = 2
                                    };
                                    c.MT_Call <object>("Divide", a, true)._GetResult();
                                    //c.ST_CallOne<object>("Divide", a, true).Wait();
                                    b.IncrementMe++;
                                }
                            }
                                                              );

                            foreach (var thread in threads)
                            {
                                thread.WaitForEnd();
                            }

                            //c.Call.Divide(8, 2).Result.Print();
                            //c.Call.Divide(8, 2).Result.Print();
                            //c.Call.Test3(1, 2, 3).Result.Print();
                            //c.Call.Test5(1, "2").Result.ObjectToJson().Print();
                            //var fnlist = c.Call.Test6().Result;
                            ////foreach (var fn in fnlist) fn.Print();
                            //c.Call.Test7(fnlist).Result.Print();

                            //Con.WriteLine(ret.ObjectToJson());
                        }
                    }, null);

                    Con.ReadLine("Enter to quit>");

                    client_stop_flag.Set(true);

                    client_thread.WaitForEnd();
                }
        }
示例#30
0
        private void MainThread()
        {
            NextPort = 0;
            Threads  = new Dictionary <Int32, Thread>();
            eventLog1.BeginInit();
            STKTVMain.TVMain TvMain;
            DataRow          dr;
            bool             bLogged = false;

            TvMain = new STKTVMain.TVMain();

            do
            {
                if (pStopServiceEvent.WaitOne(1, false))
                {
                    try
                    {
                        //TvMain.EndInit();
                        //pRefService.InfoReport("Exiting working thread...");
                        InfoReport("Exiting working thread...");
                        pStopApprovedEvent.Set();
                        return;
                    }
                    catch (Exception Ex)
                    {
                        ErrorReport("Exiting working thread error: " + Ex.Message);

                        return;
                    }
                }
                try
                {
                    //pRefService.InfoReport("Try DB login.");
                    InfoReport("Try DB login.");
                    if (TvMain.Init(true) == true)
                    {
                        bLogged = true;
                    }
                    else
                    {
                        //pRefService.WarningReport("Unable to login, check credentials");
                        WarningReport("Unable to login, check credentials");
                        InfoReport(TvMain.GetEnvInfo());
                    }
                }
                catch (Exception Ex)
                {
                    //pRefService.ErrorReport("Login failed, try again... " + Ex.Message);
                    ErrorReport("Login failed, try again... " + Ex.Message);
                    InfoReport(TvMain.GetEnvInfo());
                }
            } while (!pStopServiceEvent.WaitOne(1000, false) && !bLogged);
            //pRefService.InfoReport("DB Initialization OK");
            InfoReport("DB Initialization OK");
            //bool isgetplantable = false;

            //ƒл¤ проверки работы сервиса
            //Int16 a = 5;
            //while (a < 6)
            //{
            //    a = 5;
            //}

            do
            {
                System.Data.DataTable oRS;
                ThreadObj             throbj = null;

                oRS = null;

                if (DivID == 0)
                {
                    oRS = TvMain.GetDBDevicePlanList();
                }
                else
                {
                    oRS = TvMain.GetDBOneDevicePlanList(DivID);
                }

                if (oRS != null)
                {
                    //isgetplantable = true;
                    NextPort = 0;
                    if (oRS.Rows.Count > 0)
                    {
                        InfoReport("Checking " + oRS.Rows.Count + " active plan(s) at " + DateTime.Now.ToString());
                        for (int i = 0; i < oRS.Rows.Count; i++)
                        {
                            try
                            {
                                dr    = oRS.Rows[i];
                                id_bd = Convert.ToInt32(dr["id_bd"].ToString());
                                //if (Threads[id_bd] == null)
                                if (!Threads.ContainsKey(id_bd))
                                {
                                    throbj = new ThreadObj();
                                    //throbj.dr = oRS.Rows[i];
                                    throbj.dr = null;
                                    throbj.dr = dr;

                                    //throbj.TvMain = TvMain;
                                    throbj.TvMain = new STKTVMain.TVMain();
                                    throbj.TvMain.Init(false);
                                    //throbj.TvMain.connect();

                                    Threads.Add(id_bd, new Thread(new ParameterizedThreadStart(this.CallThr)));
                                    Threads[id_bd].SetApartmentState(ApartmentState.MTA);
                                    Threads[id_bd].Name = "Service thread " + id_bd.ToString();
                                    //InfoReport("Starting  thread " + id_bd.ToString());
                                    Threads[id_bd].Start(throbj);
                                }
                                else
                                {
                                    if (Threads[id_bd].IsAlive == false)
                                    {
                                        throbj = new ThreadObj();
                                        //throbj.dr = oRS.Rows[i];
                                        throbj.dr = null;
                                        throbj.dr = dr;
                                        //throbj.TvMain = TvMain;
                                        throbj.TvMain = new STKTVMain.TVMain();
                                        throbj.TvMain.Init(false);
                                        Threads[id_bd] = new Thread(new ParameterizedThreadStart(this.CallThr));
                                        Threads[id_bd].SetApartmentState(ApartmentState.MTA);
                                        Threads[id_bd].Name = "Service thread " + id_bd.ToString();
                                        //InfoReport("Restarting  thread " + id_bd.ToString());
                                        Threads[id_bd].Start(throbj);
                                    }
                                }
                            }
                            catch (Exception Ex)
                            {
                                ErrorReport("Thread " + id_bd.ToString() + " error:" + Ex.Message);
                            }
                        }
                    }
                    oRS    = null;
                    throbj = null;
                }
            } while (!pStopServiceEvent.WaitOne(TvMain.RequestInterval, false));

            try
            {
                InfoReport("Closing STKService...");
                Threads.Clear();
                Threads = null;
                dr      = null;

                // close nport library
                TvMain.EndInit(true);
                TvMain.CloseDBConnection();
                TvMain = null;
                //eventLog1.Close();
                eventLog1.Dispose();
                return;
            }
            catch (Exception Ex)
            {
                ErrorReport("Closing STKService error:" + Ex.Message);
            }
        }
示例#31
0
    // 実行スレッド
    void pingerThreadProc(object?param)
    {
        string optionsStr = this.DefaultOptions; // まずデフォルトのオプション文字列を読む

        string hostname = TargetHost;

        if (hostname._InStri("@"))
        {
            if (hostname._GetKeyAndValue(out string hostname2, out string tmp, "@"))
            {
                hostname = hostname2;

                // オプション文字列が個別に指定されていた場合は、それを先に付ける。同じ項目について上書きをすることになる、
                optionsStr = tmp._NonNull() + "," + optionsStr;
            }
        }

        // オプション文字列のパース
        var options = QueryStringList.Parse(optionsStr, splitChar: ',', trimKeyAndValue: true);

        // IP アドレスバージョンの決定
        AllowedIPVersions allowedIPVersions = AllowedIPVersions.All;

        string ipVerStr = options._GetStrFirst("ipver");

        if (ipVerStr._InStr("4") && ipVerStr._InStr("6") == false)
        {
            allowedIPVersions = AllowedIPVersions.IPv4;
        }
        else if (ipVerStr._InStr("6") && ipVerStr._InStr("4") == false)
        {
            allowedIPVersions = AllowedIPVersions.IPv6;
        }

        bool preferV6 = false;

        string ipperfer = options._GetStrFirst("ipprefer");

        if (ipperfer._InStri("6"))
        {
            preferV6 = true;
        }

        IPAddress GetIpAddress(string hostname, AllowedIPVersions allowedIPVersions)
        {
            var ip = hostname._ToIPAddress(allowedIPVersions, true);

            if (ip != null)
            {
                return(ip);
            }

            return(this.DnsClient.GetIpAddressAsync(hostname, allowedIPVersions, preferV6, noCache: true)._GetResult());
        }

        if (TargetPort == 0)
        {
            // ping の実行
            try
            {
                IPAddress ip = GetIpAddress(hostname, allowedIPVersions);

                SendPingReply ret = SendPing.Send(ip, null, Timeout);

                lock (lockObj)
                {
                    ok       = ret.Ok;
                    finished = true;
                }
            }
            catch
            {
                lock (lockObj)
                {
                    ok       = false;
                    finished = true;
                }
            }

            Console.Write(ok ? "+" : "-");
        }
        else
        {
            int  port      = TargetPort;
            bool tcp_check = false;

            if (port >= 100000)
            {
                port     -= 100000;
                tcp_check = true;
            }

            // TCP Connect の実行
            try
            {
                if (tcp_check == false)
                {
                    IPAddress ip = GetIpAddress(hostname, allowedIPVersions);

                    Sock s = Sock.Connect(ip.ToString(), port, Timeout, true, true);

                    try
                    {
                        if (TcpSendData)
                        {
                            s.SetTimeout(Timeout);

                            long end_tick    = Time.Tick64 + (long)Timeout;
                            int  num_packets = 0;

                            while (true)
                            {
                                if (Time.Tick64 > end_tick)
                                {
                                    break;
                                }

                                if (num_packets >= 16)
                                {
                                    break;
                                }

                                byte[] data = new byte[1];
                                data[0] = (byte)'a';
                                if (s.SendAll(data) == false)
                                {
                                    break;
                                }

                                ThreadObj.Sleep(1);
                                num_packets++;
                            }
                        }

                        s.Disconnect();
                    }
                    catch
                    {
                    }
                }
                else
                {
                    IPAddress ip = GetIpAddress(hostname, allowedIPVersions);

                    if (tcp_check_do(ip.ToString(), port, Timeout) == false)
                    {
                        throw new ApplicationException();
                    }
                }

                lock (lockObj)
                {
                    ok       = true;
                    finished = true;
                }
            }
            catch
            {
                lock (lockObj)
                {
                    ok       = false;
                    finished = true;
                }
            }

            Console.Write(ok ? "*" : "-");
        }

        //EndEvent.Set();
    }