Set() public method

public Set ( ) : bool
return bool
Exemplo n.º 1
1
        public static void Main(string[] args)
        {

            var done = new EventWaitHandle(false, EventResetMode.AutoReset);

            var yield = new Thread(
                new ParameterizedThreadStart(
                    data =>
                    {
                        Console.WriteLine(new { data });

                        done.Set();
                    }
                )
            );

            Console.WriteLine("before wait " + DateTime.Now);

            // Additional information: Thread has not been started.
            done.WaitOne(2100);

            Console.WriteLine("after wait " + DateTime.Now);

            yield.Start(new { foo = "bar" });

            done.WaitOne();

            Console.WriteLine("done");

            CLRProgram.CLRMain();
        }
Exemplo n.º 2
0
        public void ThreadDiffusionStep(object o)
        {
            fluid.UpdateDensityStep(viscoscity, frame_dt, chunkX, chunkY, NCount, startIdxX, startIdxY);

            if (System.Threading.Interlocked.Decrement(ref numberOfWorkers) == 0)
            {
                AllWorkersCompleted.Set();
            }
        }
        public void StartMission(string missionName)
        {
            var down = Program.Downloader.GetResource(DownloadType.MISSION, missionName);
            if (down == null)
            {
                //okay Mission exist, but lets check for dependency!
                down = Program.Downloader.GetDependenciesOnly(missionName);
            }

            var engine = Program.Downloader.GetResource(DownloadType.ENGINE, Program.TasClient.ServerWelcome.Engine ?? GlobalConst.DefaultEngineOverride);

            var metaWait = new EventWaitHandle(false, EventResetMode.ManualReset);
            Mod modInfo = null;
            Program.MetaData.GetModAsync(missionName,
                mod =>
                {
                    if (!mod.IsMission)
                    {
                        Program.MainWindow.InvokeFunc(() => { WarningBar.DisplayWarning(string.Format("{0} is not a valid mission", missionName)); });
                    }

                    else modInfo = mod;

                    metaWait.Set();
                },
                error =>
                {
                    Program.MainWindow.InvokeFunc(() =>
                    {
                        WarningBar.DisplayWarning(string.Format("Download of metadata failed: {0}", error.Message));
                        //container.btnStop.Enabled = true;
                    });
                    metaWait.Set();
                });

            var downloads = new List<Download>() { down, engine }.Where(x => x != null).ToList();
            if (downloads.Count > 0)
            {
                var dd = new WaitDownloadDialog(downloads);
                if (dd.ShowDialog(Program.MainWindow) == DialogResult.Cancel)
                {
                    Program.MainWindow.InvokeFunc(() => Program.NotifySection.RemoveBar(this));
                    return;
                }
            }
            metaWait.WaitOne();

            var spring = new Spring(Program.SpringPaths);
            spring.RunLocalScriptGame(modInfo.MissionScript, Program.TasClient.ServerWelcome.Engine ?? GlobalConst.DefaultEngineOverride);
            var cs = GlobalConst.GetContentService();
            cs.NotifyMissionRun(Program.Conf.LobbyPlayerName, missionName);
            spring.SpringExited += (o, args) => RecordMissionResult(spring, modInfo);
            Program.MainWindow.InvokeFunc(() => Program.NotifySection.RemoveBar(this));
        }
Exemplo n.º 4
0
        /// <summary>
        /// 测试回调
        /// </summary>
        /// <param name="value"></param>
        internal static void OnAdd(AutoCSer.Net.TcpServer.ReturnValue <AutoCSer.TestCase.TcpServerPerformance.Add> value)
        {
            int right;

            if (value.Value.CheckSum(Left, out right) != 0 || !addMap.SetWhenNullUnsafe(right))
            {
                ++ErrorCount;
            }
            if (--waitCount == 0)
            {
                Time.Stop();
                WaitHandle.Set();
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// 测试回调
        /// </summary>
        /// <param name="value"></param>
        internal static void OnAdd(AutoCSer.Net.TcpServer.ReturnValue <AutoCSer.TestCase.TcpServerPerformance.Add> value)
        {
            int right;

            if (value.Value.CheckSum(Left, out right) != 0 || !addMap.SetWhenNullUnsafe(right))
            {
                ++ErrorCount;
            }
            //if (System.Threading.Interlocked.Decrement(ref waitCount) == 0)
            if (--waitCount == 0)
            {
                Time.Stop();
                WaitHandle.Set();
            }
        }
Exemplo n.º 6
0
        private static bool OnlyOneCopy()
        {
            bool isnew;
            s_setup_mutex = new Mutex(true, SETUP_MUTEX_NAME, out isnew);

            RestoreEvent = null;
            try
            {
#if RELEASE
                RestoreEvent = AutoResetEvent.OpenExisting(EVENT_NAME);
                RestoreEvent.Set();
                return false;
            }
            catch (WaitHandleCannotBeOpenedException)
            {
#endif
                string user = Environment.UserDomainName + "\\" + Environment.UserName;
                EventWaitHandleSecurity evh_sec = new EventWaitHandleSecurity();

                EventWaitHandleAccessRule rule = new EventWaitHandleAccessRule(user,
                    EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify,
                    AccessControlType.Allow);
                evh_sec.AddAccessRule(rule);

                bool was_created;
                RestoreEvent = new EventWaitHandle(false, EventResetMode.AutoReset, 
                    EVENT_NAME, out was_created, evh_sec);
            }
            catch (Exception)
            {
            }

            return true;
        }
Exemplo n.º 7
0
 public Controller(BlockingMediator mediator)
 {
     _signal = new AutoResetEvent(false);
     mediator.AddSignal(_signal);
     dynamic config = ConfigurationManager.GetSection("delays");
     var delays = new Dictionary<MessageType, int>();
     foreach (string name in config)
     {
         delays[Hearts.Utility.Enum.Parse<MessageType>(name)] =
             int.Parse(config[name]);
     }
     foreach (var type in Hearts.Utility.Enum.GetValues<MessageType>())
     {
         var key = type;
         mediator.Subscribe(type, ignore =>
             {
                 if (delays.ContainsKey(key))
                 {
                     Thread.Sleep(delays[key]);
                 }
                 _signal.Reset();
                 if (!IsBlocking)
                 {
                     ThreadPool.QueueUserWorkItem(_ => _signal.Set());
                 }
             });
     }
 }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            // Create a IPC wait handle with a unique identifier.
            bool createdNew;
            var waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, "ImperatorWaitHandle", out createdNew);

            // If the handle was already there, inform the other process to exit itself.
            // Afterwards we'll also die.
            if (!createdNew)
            {
                Console.WriteLine("Found other Imperator process. Requesting stop...");
                waitHandle.Set();
                Console.WriteLine("Informer exited.");

                return;
            }

            Console.WriteLine("Initializing Container...");
            var container = new ContainerInitializer().Initialize();

            Console.WriteLine("Connecting to UI...");
            var hubClient = container.GetInstance<IHubClient>();
            hubClient.OpenConnection();
            Console.WriteLine("Connected");

            Console.WriteLine("Initializing Imperator...");
            var i = container.GetInstance<Imperator>();
            i.InitializeConfig();
            i.StartImperator();

            waitHandle.WaitOne();
            Console.WriteLine("Closing Imperator...");
        }
Exemplo n.º 9
0
 public DoubleLaunchLocker(string signalId, string waitId, bool force = false)
 {
     _force = force;
     SignalId = signalId;
     WaitId = waitId;
     bool isNew;
     _signalHandler = new EventWaitHandle(false, EventResetMode.AutoReset, signalId, out isNew);
     if (!isNew)
     {
         Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
         bool terminate = false;
         if (!force && !RequestConfirmation())
             terminate = true;
         if (!terminate)
         {
             _waitHandler = new EventWaitHandle(false, EventResetMode.AutoReset, waitId);
             if (_signalHandler.Set())
                 terminate = !_waitHandler.WaitOne(TIMEOUT);
             else
                 terminate = true;
         }
         if (terminate)
         {
             TryShutdown();
             ForceShutdown();
         }
         else
             Application.Current.ShutdownMode = ShutdownMode.OnLastWindowClose;
     }
     ThreadPool.QueueUserWorkItem(WaitingHandler, waitId);
 }
Exemplo n.º 10
0
        public void ShouldJoinDirectMessageChannel()
        {
            // given
            var client = ClientHelper.GetClient(_config.Slack.UserAuthToken);

            string userName = _config.Slack.DirectMessageUser;
            string user = client.Users.First(x => x.name.Equals(userName, StringComparison.InvariantCultureIgnoreCase)).id;

            // when
            EventWaitHandle wait = new EventWaitHandle(false, EventResetMode.ManualReset);
            client.JoinDirectMessageChannel(response =>
            {
                Assert.IsTrue(response.ok, "Error while joining user channel");
                Assert.IsTrue(!string.IsNullOrEmpty(response.channel.id), "We expected a channel id to be returned");
                wait.Set();
            }, user);

            // then
            Policy
                .Handle<AssertFailedException>()
                .WaitAndRetry(15, x => TimeSpan.FromSeconds(0.2), (exception, span) => Console.WriteLine("Retrying in {0} seconds", span.TotalSeconds))
                .Execute(() =>
                {
                    Assert.IsTrue(wait.WaitOne(), "Took too long to do the THING");
                });
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.AutoReset, uniqueHandleName);

            AppDomain appDomain1 = AppDomain.CreateDomain("App Domain 1");

            Thread thread1 = new Thread(new ThreadStart(() => appDomain1.DoCallBack(() =>
                {
                    EventHandleResponder responder = new EventHandleResponder();
                    responder.Run();
                })));

            thread1.Start();

            Console.WriteLine("Enter 1 to set the signal on the wait handle.");
            Console.WriteLine("Enter q to quit.");

            string input = string.Empty;

            while (input != "quit" && input != "q")
            {
                input = Console.ReadLine();

                switch (input)
                {
                    case "1":
                        handle.Set();
                        break;
                }
            }
        }
Exemplo n.º 12
0
        public AbsoluteTimerWaitHandle(DateTimeOffset dueTime)
        {
            _dueTime = dueTime;
            _eventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);

            SafeWaitHandle = _eventWaitHandle.SafeWaitHandle;

            var dueSpan = (_dueTime - DateTimeOffset.Now);
            var period = new TimeSpan(dueSpan.Ticks / 10);

            if (dueSpan < TimeSpan.Zero)
            {
                _eventWaitHandle.Set();
            }
            else
            {
                _timer = new Timer(period.TotalMilliseconds)
                {
                    AutoReset = false,
                };

                _timer.Elapsed += TimerOnElapsed;

                _timer.Start();
            }
        }
Exemplo n.º 13
0
        public void Should_be_able_to_cancel_message_reception_with_a_cancellation_token()
        {
            const string mmfName = "Local\\test";
            var message = "not null";
            var messageCancelled = new EventWaitHandle(false, EventResetMode.ManualReset, mmfName + "_MessageCancelled");

            messageCancelled.Set();

            using (var messageReceiver = new MemoryMappedFileMessageReceiver(mmfName))
            using (var cancellationTokenSource = new CancellationTokenSource())
            {
                var task = new Task(() => message = messageReceiver.ReceiveMessage(ReadString, cancellationTokenSource.Token));

                task.Start();

                var isSet = true;

                while (isSet)
                    isSet = messageCancelled.WaitOne(0);

                cancellationTokenSource.Cancel();

                task.Wait();

                message.ShouldBeNull();
            }
        }
Exemplo n.º 14
0
        void AuthSignIn()
        {
            EventWaitHandle wait = new EventWaitHandle(false, EventResetMode.ManualReset);
            SlackSocketClient client = new SlackSocketClient(token);
            client.OnHello += () =>
            {
                wait.Set();
            };
            client.Connect((l) =>
            {

                if (!l.ok) return;

                BeginInvoke(new Action(() =>
                {
                    connected = new ConnectedInterface(client, l);
                    connected.Dock = DockStyle.Fill;

                    Controls.Add(connected);

                    password.Visible = false;
                }));
            });
            wait.WaitOne();
        }
Exemplo n.º 15
0
        public void Should_be_able_to_cancel_message_reception_upon_disposal()
        {
            const string mmfName = "Local\\test";
            var message = "not null";
            var messageCancelled = new EventWaitHandle(false, EventResetMode.ManualReset, mmfName + "_MessageCancelled");

            messageCancelled.Set();

            var messageReceiver = new MemoryMappedFileMessageReceiver(mmfName);

            var task = new Task(() => message = messageReceiver.ReceiveMessage(ReadString));

            task.Start();

            var isSet = true;

            while (isSet)
                isSet = messageCancelled.WaitOne(0);

            messageReceiver.Dispose();

            task.Wait();

            message.ShouldBeNull();
        }
Exemplo n.º 16
0
 public void ServerResponds() {
   using (var container = SetupMefContainer()) {
     using (var server = container.GetExport<IServerProcessProxy>().Value) {
       var waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
       var request = new IpcRequest {
         RequestId = 5,
         Protocol = IpcProtocols.Echo,
         Data = new IpcStringData {
           Text = "sdfsdsd"
         }
       };
       IpcResponse response = null;
       server.RunAsync(request, x => {
         response = x;
         waitHandle.Set();
       });
       Assert.IsTrue(waitHandle.WaitOne(TimeSpan.FromSeconds(5.0)), "Server did not respond within 5 seconds.");
       Assert.AreEqual(5, response.RequestId);
       Assert.AreEqual(IpcProtocols.Echo, response.Protocol);
       Assert.IsNotNull(request.Data);
       Assert.IsNotNull(response.Data);
       Assert.AreEqual(request.Data.GetType(), typeof(IpcStringData));
       Assert.AreEqual(response.Data.GetType(), typeof(IpcStringData));
       Assert.AreEqual((request.Data as IpcStringData).Text, (response.Data as IpcStringData).Text);
     }
   }
 }
Exemplo n.º 17
0
        static void RunInThreadPoolWithEvents()
        {
            double result = 0d;

            // We use this event to signal when the thread is don executing.
            EventWaitHandle calculationDone = new EventWaitHandle(false, EventResetMode.AutoReset);

            // Create a work item to read from I/O
            ThreadPool.QueueUserWorkItem((x) => {
                result += Utils.CommonFunctions.ReadDataFromIO();
                calculationDone.Set();
            });

            // Save the result of the calculation into another variable
            double result2 = Utils.CommonFunctions.DoIntensiveCalculations();

            // Wait for the thread to finish
            calculationDone.WaitOne();

            // Calculate the end result
            result += result2;

            // Print the result
            Console.WriteLine("The result is {0}", result);
        }
Exemplo n.º 18
0
        public static SlackSocketClient GetClient(string authToken)
        {
            var wait = new EventWaitHandle(false, EventResetMode.ManualReset);

            var client = new SlackSocketClient(authToken);
            client.Connect(x =>
            {
                Console.WriteLine("RTM Start");
            }, () =>
            {
                Console.WriteLine("Connected");
                wait.Set();
            });

            Policy
                .Handle<AssertFailedException>()
                .WaitAndRetry(15, x => TimeSpan.FromSeconds(0.2), (exception, span) => Console.WriteLine("Retrying in {0} seconds", span.TotalSeconds))
                .Execute(() =>
                {
                    Assert.IsTrue(wait.WaitOne(), "Still waiting for things to happen...");
                });

            Policy
                .Handle<AssertFailedException>()
                .WaitAndRetry(15, x => TimeSpan.FromSeconds(0.2), (exception, span) => Console.WriteLine("Retrying in {0} seconds", span.TotalSeconds))
                .Execute(() =>
                {
                    Assert.IsTrue(client.IsConnected, "Doh, still isn't connected");
                });

            return client;
        }
Exemplo n.º 19
0
    private void DebuggerStart(EventWaitHandle startWaitHandle, Func<ProcessInformation> processCreator, Action<ProcessInformation> callback, Action<Exception> errorCallback) {
      try {
        _debuggerThread = Thread.CurrentThread;
        // Note: processCreator is responsible for creating the process in DEBUG mode.
        // Note: If processCreator throws an exception after creating the
        // process, we may end up in a state where we received debugging events
        // without having "_processInformation" set. We need to be able to deal
        // with that.
        _processInformation = processCreator();
        callback(_processInformation);
      }
      catch (Exception e) {
        errorCallback(e);
        return;
      }
      finally {
        startWaitHandle.Set();
      }

      _running = true;
      try {
        DebuggerLoop();
      }
      finally {
        _running = false;
      }
    }
Exemplo n.º 20
0
        private void StartClientServer(object obj)
        {
            try
            {
                int clientServerPort = (int)obj;
                s_Logger.LogInfo("IMissionControl::ClientThe port sent from server is " + clientServerPort.ToString());
                MarshalByRefObject processProxyObject = GetProcessProxy();//factory
                TcpServerChannel   clientServer       = new TcpServerChannel("WinSniperClient", clientServerPort);
                ChannelServices.RegisterChannel(clientServer, true);

                RemotingServices.Marshal(processProxyObject, "WinSniperClient.rem");
                s_Logger.LogInfo("Sniper ClientServer has been started and listening at " + clientServerPort.ToString());


                System.Threading.EventWaitHandle wh = EventWaitHandle.OpenExisting("SniperWaiting", EventWaitHandleRights.Modify);
                wh.Set();
                while (true)
                {
                    Thread.Sleep(1000);
                }
            }
            catch (ThreadAbortException e)
            {
                s_Logger.LogError("Client Server Thread has been aborted. ");
            }
            catch (Exception e)
            {
                new Mayday(e);
            }
        }
Exemplo n.º 21
0
 public Waiter(TimeSpan? interval = null)
 {
     _waitHandle = new AutoResetEvent(false);
     _timer = new System.Timers.Timer();
     _timer.Elapsed += (sender, args) => _waitHandle.Set();
     SetInterval(interval);
 }
Exemplo n.º 22
0
        public static void Main(string[] args)
        {
            var dir = @"c:\tmp";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            ewh = new EventWaitHandle(false, EventResetMode.ManualReset);

            for (int i = 0; i <= 10; i++)
            {
                var t = new Thread(ThreadProc);
                t.Start(i);
                Console.WriteLine("Tread {0} started", i);
            }

            watcher = new FileSystemWatcher()
            {
                Path = dir,
                IncludeSubdirectories = false,
                EnableRaisingEvents = true,
            };

            watcher.Created += (sender, eventArgs) =>
            {
                 ewh.Set();
            };

            Console.WriteLine("Press any key....");
            Console.ReadLine();
        }
Exemplo n.º 23
0
 public void OnNext(bool value)
 {
     if (value == true)
     {
         eventWaitHandle.Set();
     }
 }
        /// <summary>
        /// Fetches the Dota 2 Item schema.
        /// </summary>
        /// <param name="apiKey">The API key.</param>
        /// <returns>A  deserialized instance of the Item Schema.</returns>
        /// <remarks>
        /// The schema will be cached for future use if it is updated.
        /// </remarks>
        public static Dota2Schema FetchSchema (string apiKey)
        {   
            var url = SchemaApiUrlBase + apiKey;

            // just let one thread/proc do the initial check/possible update.
            bool wasCreated;
            var mre = new EventWaitHandle(false, 
                EventResetMode.ManualReset, SchemaMutexName, out wasCreated);

            // the thread that create the wait handle will be the one to 
            // write the cache file. The others will wait patiently.
            if (!wasCreated)
            {
                bool signaled = mre.WaitOne(10000);

                if (!signaled)
                {
                    return null;
                }
            }

            HttpWebResponse response = SteamWeb.Request(url, "GET");
            DateTime schemaLastModified = response.LastModified;
            string result = GetSchemaString(response, schemaLastModified);
            response.Close();
            mre.Set();

            SchemaResult schemaResult = JsonConvert.DeserializeObject<SchemaResult> (result);
            return schemaResult.result ?? null;
        }
Exemplo n.º 25
0
 public void Reset(int count) {
     if (count < 0)
         throw new ArgumentOutOfRangeException();
     _remaining = count;
     _event = new ManualResetEvent(false);
     if (_remaining == 0)
         _event.Set();
 }
Exemplo n.º 26
0
        public void Learn()
        {
            ewh=new EventWaitHandle(false,EventResetMode.AutoReset);

            for (int i = 0; i <=4; i++)
            {
                Thread t=new Thread(new ParameterizedThreadStart(ThreadProc));
                t.Start(i);
            }

            while (Interlocked.Read(ref threadCount)<5)
            {
                Thread.Sleep(500);
            }

            while (Interlocked.Read(ref threadCount)>0)
            {
                Console.WriteLine("Press Enter to release a waiting thread.");
                Console.ReadLine();
                clearCount.Set();
                WaitHandle.SignalAndWait(ewh, clearCount);
                Console.WriteLine("loop again.");
            }
            Console.WriteLine();

            ewh=new EventWaitHandle(false,EventResetMode.ManualReset);

            for (int i = 0; i <=4; i++)
            {
                Thread t=new Thread(new ParameterizedThreadStart(ThreadProc));
                t.Start(i);
            }

            while (Interlocked.Read(ref threadCount)<5)
            {
                Thread.Sleep(500);
            }

            Console.WriteLine("Press ENTER to release the waiting threads");
            Console.ReadLine();
            ewh.Set();
            ewh.Reset();
            Console.WriteLine("Press ENTER to release the waiting threads");
            Console.ReadLine();
            ewh.Set();
        }
Exemplo n.º 27
0
        /// <summary>
        /// Scans a given page for proxy servers.
        /// </summary>
        /// <param name="proxyListingPage">The proxy listing page.</param>
        /// <param name="parseAsRawText">If the page must be parsed as raw text (no HTML tags)</param>
        /// <param name="hostPortEx">The custom parsing expression (providing "address" or "host" and "port" tags) or null to use default</param>
        /// <param name="route"></param>
        /// <param name="testTarget"></param>
        /// <returns></returns>
        public IEnumerable<ProxyServer> ScanPage(Uri proxyListingPage, bool parseAsRawText, string hostPortEx, Route route, Uri testTarget)
        {
            string proxyListingPageText = null;
            try
            {
                proxyListingPageText = Downloader.Download(proxyListingPage, parseAsRawText, route);
            }
            catch (ProxyRouteException)
            { }
            if (proxyListingPageText == null)
                yield break;

            var results = new Queue<ProxyServer>();
            var waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
            var thread = new Thread(delegate()
            {
                HostScanner.Scan(proxyListingPageText, hostPortEx).AsParallel().WithDegreeOfParallelism(63)
                    .ForAll(delegate(ProxyServer proxyServer)
                    {
                        if (!ProxyValidator.Validate(proxyServer, testTarget, route))
                            return;
                        lock (results)
                            results.Enqueue(proxyServer);
                        waitHandle.Set();
                    });
                lock (results)
                    results.Enqueue(null);
                waitHandle.Set();
            });
            thread.Start();
            for (; ; )
            {
                waitHandle.WaitOne();
                lock (results)
                {
                    while (results.Count > 0)
                    {
                        var result = results.Dequeue();
                        if (result == null)
                            yield break;
                        yield return result;
                    }
                }
            }
        }
Exemplo n.º 28
0
        private Task<bool> StopGracefully(IProcess process)
        {
            string exePath = process.ExePath;
            Trace.TraceInformation("Attempting to gracefully stop the process");
            var stopEvent = new EventWaitHandle(false, EventResetMode.AutoReset, exePath.Replace("\\", string.Empty));
            stopEvent.Set();

            return ProcessUtils.SpinWaitForExit(process, _waitForExitInSeconds);
        }
Exemplo n.º 29
0
 unsafe void ThreadFunc()
 {
     eventWH = new EventWaitHandle(false, EventResetMode.AutoReset, "ulHelper_appLiveEvent_" + acc.Name);
     while (!acc.NeedTerminate)
     {
         Thread.Sleep(100);
         eventWH.Set();
     }
 }
Exemplo n.º 30
0
		public void Disposed_Set ()
		{
			var ewh = new EventWaitHandle (false, EventResetMode.ManualReset);
			ewh.Dispose();
			try {
				ewh.Set();
				Assert.Fail ();
			} catch (ObjectDisposedException) {
			}
		}
Exemplo n.º 31
0
        public void Connect()
        {
            if (!IsRunning)
            {
                Thread worker = new Thread(() =>
                {
                    try
                    {
                        IsRunning = true;
                        _shouldStop = false;

                        wait = new EventWaitHandle(false, EventResetMode.ManualReset);
                        client.Connect(1000);
                        if (client.IsConnected)
                        {
                            while (!_shouldStop)
                            {
                                byte[] m_buffer = new byte[256];
                                client.BeginRead(m_buffer, 0, 255, ir =>
                                {
                                    try
                                    {
                                        client.EndRead(ir);
                                        wait.Set();
                                    }
                                    catch (Exception ex)
                                    {
                                        if (!(ex is ArgumentException))
                                            Debugger.Break();

                                    }
                                }, null);
                                wait.WaitOne();
                            }
                        }

                        IsRunning = false;
                    }
                    catch (Exception ex)
                    {
                        if (ex is TimeoutException)
                            Console.WriteLine("Unable to connect to CWSRestart. Make sure that the process communication is enabled in CWSRestart");
                        else
                            System.Diagnostics.Debugger.Break();
                        IsRunning = false;
                    }
                });

                worker.Start();
            }
            else
            {
                Console.WriteLine("Communication is already running.");
            }
        }
Exemplo n.º 32
0
        static void Main()
        {
            var model = new Model{ ObjectSensorConfig = VideoSource.USB };
            model.ServosConfig[ServoPort.C1] = Defaults.Servo3;
            model.ServosConfig[ServoPort.C2] = Defaults.Servo3;

            var sensor = model.ObjectSensor;
            var sensorOutput = sensor.ToObservable();

            var locationStream = from data in sensorOutput
                                 where data.IsLocation
                                 let loc = data.GetLocation
                                 where loc.Mass > Constants.MinMass
                                 select loc;
            //var locationStream = sensor.ToObservable()
            //                    .Where(o => o.IsLocation).Select(o => o.GetLocation)
            //                    .Where(loc => loc.Mass > Constants.MinMass);

            var xPowerSetter = locationStream
                .Select(loc => -loc.X)
                .Scan(0, (acc, x) => Calculations.Limit(-90, 90, acc) + ScaleXValue(x))
                .Subscribe(model.Servos[ServoPort.C1]);

            var yPowerSetter = locationStream
                .Select(loc => loc.Y)
                .Scan(0, (acc, y) => Calculations.Limit(-90, 90, acc) + ScaleYValue(y))
                .Subscribe(model.Servos[ServoPort.C2]);

            var buttons = model.Buttons;
            var exit = new EventWaitHandle(false, EventResetMode.AutoReset);

            var targetStream = from data in sensorOutput
                               where data.IsTarget
                               select data.GetTarget;

            var setterDisposable = targetStream.Subscribe(sensor.SetDetectTarget);

            var observableButtons = buttons.ToObservable();

            var downButtonDetect =
                observableButtons
                    .Where(x => ButtonEventCode.Down == x.Button)
                    .Subscribe(x => sensor.Detect());

            var upButtonDispose =
                observableButtons
                .Where(x => ButtonEventCode.Up == x.Button)
                .Subscribe(x => exit.Set());

            buttons.Start();
            sensor.Start();
            Shell.Send(@"v4l2-ctl -d ""/dev/video2"" --set-ctrl white_balance_temperature_auto=1");

            exit.WaitOne();
        }
        public ActionResult Command(String deviceId, int timeout = 60)
        {
            EventWaitHandle waitHandle;

            using (mongoContext = Context.MongoDBContext.MongoContextFactory.GetContext())
            using (rabbitContext = Context.RabbitMqContext.RabbitMqContextFactory.GetContext())
            {
                JObject command = rabbitContext.GetCommand(deviceId);
                if (command == null)
                {

                    //загрузка ЦП на самом деле не меняется абсолютно
                    waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);

                    NewCommandSignal sign = delegate(String devId)
                    {
                        if (deviceId == devId)
                        {
                            command = rabbitContext.GetCommand(deviceId);
                            waitHandle.Set();
                        }
                    };

                //на момент написания этого кода у меня похоже недостаточно опыта в WCF чтобы элегантно реализвать long polling
                // в асинхронном виде. да еще встроить в ASP.net контроллер. есть в документации аттрбут AsyncPattern для контракта. если удасться, к понедельнику переделаю
                //c использованием WCF. хотя что-то мне подсказывает, что я должен был сделать не на ASP.net при использовании WCF, а просто на WCF

                    onNewCommand += sign;

                    waitHandle.WaitOne((Int32)timeout * 1000);

                    onNewCommand -= sign;

                    if (onRequestProcessed != null)
                        onRequestProcessed.Invoke(command);
                    if (command != null)
                    {
                        return Json((Models.DSRCommand)command.ToObject(typeof(Models.DSRCommand)), JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        return Json(null, JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    String js = command.ToString();
                    if (onRequestProcessed != null)
                        onRequestProcessed.Invoke(command);

                    return Json((Models.DSRCommand)command.ToObject(typeof(Models.DSRCommand)), JsonRequestBehavior.AllowGet);
                }
            }
        }
Exemplo n.º 34
0
        private static async Task Start(EventWaitHandle exit)
        {
            IBus bus = await SetupBus();
            
            var fireHoseSender = new FireHoseSender(bus);

            Console.WriteLine("How many messages would you like to spray?");

            while (true)
            {
                var consoleInput = Console.ReadLine();

                if (string.IsNullOrWhiteSpace(consoleInput))
                {
                    Console.WriteLine("Please enter number or type 'Exit'");
                }
                else
                {
                    if (consoleInput.ToLowerInvariant() == "exit")
                    {
                        exit.Set();
                        break;
                    }

                    int numberOfMessages;

                    if (!int.TryParse(consoleInput, out numberOfMessages))
                    {
                        Console.WriteLine("Please enter a valid number");
                        continue;

                    }

                    await fireHoseSender.SprayMessages(numberOfMessages);
                    break;
                }
            }

            Console.ReadKey();
            exit.Set();
        }
Exemplo n.º 35
0
        public static void BeginProgram(bool isStep)
        {
            if (isRunning && !isStep)
            {
                isRunning = false;
                waitHandle.Set();
            }
            var t = new Thread(() => ExecuteProgram(isStep));

            t.IsBackground = true;
            t.Start();
        }
Exemplo n.º 36
0
        public Task Execute()
        {
            TestLib.DispatchContainer.GlobalDispatcher = vm_.Dispatcher;

            return Task.Run(async () =>
            {
                try
                {
                    var testContainer = GetTestingAssembly();
                    int failureCount = 0, totalCount = 0;
                    foreach (Type testType in GetTestTypes(testContainer))
                    {
                        UnitTest test = (UnitTest)Activator.CreateInstance(testType);
                        test.Log = log_;
                        int testFailures = 0;

                        foreach (var methodDesc in GetTestMethods(testType))
                        {
                            test.Assert.TestName = methodDesc.Method.DeclaringType.Name + "." + methodDesc.Method.Name;
                            if (methodDesc.RunInDispatcherContext)
                            {
                                EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.AutoReset);
                                test.Assert.WaitHandle = wh;
                                await vm_.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                                {
                                    testFailures = await ExecuteTest(test, testFailures, methodDesc);
                                    wh.Set();
                                });
                                wh.WaitOne(methodDesc.Timeout);
                            }
                            else
                            {
                                testFailures = await ExecuteTest(test, testFailures, methodDesc);
                            }
                        }

                        failureCount += testFailures;
                        totalCount += test.Assert.Count;
                        vm_.AddMessage(string.Format("Completed '{0}' [{1} assertion(s), {2} failure(s)]", testType.Name, test.Assert.Count, testFailures));
                        vm_.UpdateMessages();
                    }

                    vm_.AddMessage(string.Format("All tests completed [{0} assertion(s), {1} failure(s)]", totalCount, failureCount));
                    vm_.UpdateMessages();
                }
                catch (Exception ex)
                {
                    if (Debugger.IsAttached)
                        Debugger.Break();
                }
            });
        }
Exemplo n.º 37
0
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            logIt(e.ToString());
            Exception ex = default(Exception);

            ex = (Exception)e.ExceptionObject;
            logIt(ex.StackTrace);
            if (ewait != null)
            {
                ewait.Set();
                //ewait.Close();
            }
            //
        }
Exemplo n.º 38
0
    //bool logged;
    // Update is called once per frame
    void Update()
    {
        lidar();
        position();
        distanceFromFlag();

        if (!updated)
        {
            updatePostion();
            updated = true;
            waitHandle.Set();
        }

        //travelled();
    }
Exemplo n.º 39
0
 public void Start()
 {
     if (alreadyStarted)
     {
         lock (forState)
             this.internalState = ThreadState.Running;
         restart.Set();
     }
     else
     {
         alreadyStarted = true;
         lock (forState)
             this.internalState = ThreadState.Running;
         this.gThread.Start();
     }
 }
Exemplo n.º 40
0
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            logIt(e.ToString());
            Exception ex = default(Exception);

            ex = (Exception)e.ExceptionObject;
            logIt(ex.StackTrace);
            if (ewait != null)
            {
                ewait.Set();
                //ewait.Close();
            }
            Thread.Sleep(5000);
            Util.runExeOnly(System.Reflection.Assembly.GetEntryAssembly().Location, "-start-service");
            Environment.Exit(1000);
        }
Exemplo n.º 41
0
 void ICallback.Response(MercuryResponse response)
 {
     _reference = response;
     _waitHandle.Set();
 }
Exemplo n.º 42
0
 void _popup_Closed(object sender, object e)
 {
     _handle.Set();
 }
Exemplo n.º 43
0
        static void Main(string[] args)
        {
            System.Configuration.Install.InstallContext _arg = new System.Configuration.Install.InstallContext(null, args);
            if (_arg.IsParameterTrue("debug"))
            {
                System.Console.WriteLine("Wait for debugger, press any key to continue...");
                System.Console.ReadKey();
            }
            // dump version
            logIt(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileVersionInfo.ToString());
            // dump args
            logIt(string.Format("called by arg: ({0})", args.Length));
            foreach (string s in args)
            {
                logIt(s);
            }

            System.AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            if (_arg.IsParameterTrue("start-service"))
            {
                // start service
                Boolean bFind = false;
                try
                {
                    ewait = System.Threading.EventWaitHandle.OpenExisting(IdeviceInfoSvcHost_Event_Name);
                    ewait.Close();
                    logIt("Instance already started.");
                }
                catch (WaitHandleCannotBeOpenedException)
                {
                    bFind = true;
                }
                catch (Exception) { }
                if (bFind)
                {
                    try
                    {
                        ewait = new EventWaitHandle(false, EventResetMode.ManualReset, IdeviceInfoSvcHost_Event_Name);
                        //Util.InitEnviroment();

                        new Thread(() =>
                        {
                            iDeviceClass.start();
                        }).Start();
                        Console.WriteLine(@"Press any key to terminate...");
                        while (!ewait.WaitOne(1000))
                        {
                            if (System.Console.KeyAvailable)
                            {
                                ewait.Set();
                            }
                        }
                        ewait.Close();
                        iDeviceClass.stop();
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            else if (_arg.IsParameterTrue("kill-service"))
            {
                // stop service
                try
                {
                    ewait = System.Threading.EventWaitHandle.OpenExisting(IdeviceInfoSvcHost_Event_Name);
                    if (ewait != null)
                    {
                        ewait.Set();
                    }
                }
                catch (Exception) { }
            }
            else
            {
                System.Console.WriteLine("MonitoriDevice.exe");
                System.Console.WriteLine("-start-service: to start the service");
                System.Console.WriteLine("-kill-service: to stop the service");
            }
        }
Exemplo n.º 44
0
 public void Append(byte[] bytes)
 {
     this.queue.Enqueue(bytes);
     ewh.Set();
 }
Exemplo n.º 45
0
        static int Main(string[] args)  // :обновление
        {
            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath));

            repairUpdateExe();
            var repair = args.Length == 0 || (args.Length == 1 && args[0] == "-repair");

            if (Repair(repair) && repair)
            {
                Console.WriteLine("repair started - succes");
                return(40);
            }

            if (args.Length > 5 || args.Length < 4)
            {
                writeHelp();
                return(1);
            }

            mainMutexForLog.WaitOne();
            addBootRun();

            Semaphore s = null;                  //new System.Threading.Semaphore(50, 50, "vs8.ru updator semaphore");
            Mutex     syncSemaphoreMutex = null;
            int       sCount = 0, rCount = 0, mCount = 0;
            bool      updatorUpdate = false;

            try
            {
                if (args[1] == "vs8.ru updator semaphore")
                {
                    main.Set();
                    sCount        = 50;
                    updatorUpdate = true;
                }
                else
                {
                    sCount = Int32.Parse(args[2]);
                }


                if (args[1].Length > 0)
                {
                    s = new Semaphore(sCount, sCount, args[1]);
                    syncSemaphoreMutex = new Mutex(false, args[1] + " umove sync mutex");
                }

                if (syncSemaphoreMutex != null)
                {
                    if (!syncSemaphoreMutex.WaitOne(0))
                    {
                        return(32);
                    }

                    mCount = 1;
                }

                var RepairInfo = setRepairInfo(args);
                if (s != null)
                {
                    rCount = blockSemaphore(s, sCount);
                }

                var returned = umoveProcess(args);

                if (returned == 0)
                {
                    Console.WriteLine("success");
                }
                else
                {
                    Console.WriteLine("failure with code " + returned);
                }
                File.AppendAllText(errorLogFileName, String.Format(msgMessage, DateTime.Now, "Исполнено с кодом " + returned, getArgumentsFromArgArray(args)));

                if (updatorUpdate)
                {
                    File.AppendAllText(errorLogFileName, String.Format(msgMessage, DateTime.Now, "Стартуем ./updatorvs8.exe -umove", getArgumentsFromArgArray(args)));
                    Process.Start("updatorvs8.exe", "-umove");
                }

                if (args[3].Length > 0)
                {
                    if (args.Length == 4)
                    {
                        File.AppendAllText(errorLogFileName, String.Format(msgMessage, DateTime.Now, "Стартуем " + args[3], getArgumentsFromArgArray(args)));
                        Process.Start(args[3]);
                    }
                    else
                    {
                        File.AppendAllText(errorLogFileName, String.Format(msgMessage, DateTime.Now, "Стартуем " + args[3] + " " + args[4], getArgumentsFromArgArray(args)));
                        Process.Start(args[3], args[4]);
                    }
                }
                ClearRepairInfo(args, RepairInfo);

                deleteBootRun();
                File.AppendAllText(errorLogFileName, String.Format(msgMessage, DateTime.Now, "Исполнено и удалено из аварийного восстановления", getArgumentsFromArgArray(args)));

                truncateLog(new FileInfo(errorLogFileName));

                return(returned);
            }
            finally
            {
                if (s != null)
                {
                    releaseSemaphore(s, rCount);
                    s.Close();
                }

                if (syncSemaphoreMutex != null)
                {
                    if (mCount > 0)
                    {
                        syncSemaphoreMutex.ReleaseMutex();
                    }
                    syncSemaphoreMutex.Close();
                }

                main.Reset();
                main.Close();
                mainMutexForLog.ReleaseMutex();
                mainMutexForLog.Close();
            }
        }
Exemplo n.º 46
0
        static void Main(string[] args)
        {
            System.Configuration.Install.InstallContext _arg = new System.Configuration.Install.InstallContext(null, args);
            if (_arg.IsParameterTrue("debug"))
            {
                System.Console.WriteLine("Wait for debugger, press any key to continue...");
                System.Console.ReadKey();
            }
            // dump version
            logIt(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileVersionInfo.ToString());
            // dump args
            logIt(string.Format("called by arg: ({0})", args.Length));
            foreach (string s in args)
            {
                logIt(s);
            }


            IniFile ini          = new IniFile(Path.Combine(Environment.ExpandEnvironmentVariables(@"%APSTHOME%"), "config.ini"));
            String  sMaxcapacity = ini.GetString("battery", "read_ratio_reboot", "false");

            Util.IsMaxCapacity = String.Compare(sMaxcapacity, "true", true) == 0 || String.Compare(sMaxcapacity, "1", true) == 0;
            //Util.IsMaxCapacity = true;
            logIt($"config Maxcapacity = {sMaxcapacity}:{Util.IsMaxCapacity}");
            System.AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            if (_arg.IsParameterTrue("start-service"))
            {
                // start service
                Boolean bRun = false;
                try
                {
                    ewait = System.Threading.EventWaitHandle.OpenExisting(IdeviceInfoSvcHost_Event_Name);
                    ewait.Close();
                    logIt("Instance already started.");
                }
                catch (WaitHandleCannotBeOpenedException)
                {
                    bRun = true;
                }
                catch (Exception) { }
                if (bRun)
                {
                    try {
                        ewait = new EventWaitHandle(false, EventResetMode.ManualReset, IdeviceInfoSvcHost_Event_Name);
                        //Util.InitEnviroment();
                        ThreadPool.QueueUserWorkItem(new WaitCallback(Util.runMonitorExe), null);
                        using (ServiceHost host = new ServiceHost(typeof(Device)))
                        {
                            host.Open();
                            Console.WriteLine(@"go to http://localhost:1930/device to test");
                            Console.WriteLine(@"Press any key to terminate...");
                            while (!ewait.WaitOne(1000))
                            {
                                if (System.Console.KeyAvailable)
                                {
                                    ewait.Set();
                                }
                            }
                            host.Close();
                        }
                        Util.bExit = true;
                        Util.runMonitorExe("-kill-service");
                        ewait.Close();
                    } catch (Exception)
                    {
                        logIt("iTunes MobileDevice.Dll not found.************");
                    }
                    Util.bExit = true;
                    Util.runMonitorExe("-kill-service");
                    ewait.Close();
                }
            }
            else if (_arg.IsParameterTrue("kill-service"))
            {
                // stop service
                try
                {
                    ewait = System.Threading.EventWaitHandle.OpenExisting(IdeviceInfoSvcHost_Event_Name);
                    if (ewait != null)
                    {
                        ewait.Set();
                    }
                }
                catch (Exception) { }
            }
            else
            {
                System.Console.WriteLine("IdeviceInfoSvcHost.exe");
                System.Console.WriteLine("-start-service: to start the service");
                System.Console.WriteLine("-kill-service: to stop the service");
            }
        }
Exemplo n.º 47
0
 public void SetFree()
 {
     waiter.Set();
 }