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(); }
/// <summary> /// The constructor is private: loading screens should /// be activated via the static Load method instead. /// </summary> private LoadingScreen (ScreenManager screenManager,bool loadingIsSlow, GameScreen[] screensToLoad) { this.loadingIsSlow = loadingIsSlow; this.screensToLoad = screensToLoad; TransitionOnTime = TimeSpan.FromSeconds (0.5); // If this is going to be a slow load operation, create a background // thread that will update the network session and draw the load screen // animation while the load is taking place. if (loadingIsSlow) { backgroundThread = new Thread (BackgroundWorkerThread); backgroundThreadExit = new ManualResetEvent (false); graphicsDevice = screenManager.GraphicsDevice; // Look up some services that will be used by the background thread. IServiceProvider services = screenManager.Game.Services; networkSession = (NetworkSession)services.GetService ( typeof(NetworkSession)); messageDisplay = (IMessageDisplay)services.GetService ( typeof(IMessageDisplay)); } }
public BK8500(string comPortname, byte address) { instrumentError = false; //Setup serial port P = new SerialPort(comPortname, 38400); P.DataBits = 8; P.StopBits = StopBits.One; P.Parity = Parity.None; P.RtsEnable = true; P.ReadTimeout = 200; //Setup event for received data P.ReceivedBytesThreshold = packetLength; //all packets for this device are 26 bytes in length P.DataReceived += new SerialDataReceivedEventHandler(P_DataReceived); dataWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset); //this syncs the received data event handler to the main thread P.Open(); P.DiscardInBuffer(); this.address = address; //enter local mode this.remoteOperation = true; this.loadON = false; this.deviceConnected = true; }
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(); } }
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(); } }
/// <summary> /// ctor /// </summary> /// <param name="session"></param> public ResponseListener(O2GSession session) { mRequestID = string.Empty; mResponse = null; mSyncResponseEvent = new EventWaitHandle(false, EventResetMode.AutoReset); mSession = session; }
public void EndWorkerThread() { SetEndWorkerThread(); workerEndThread_evt.WaitOne(5000); m_workerThread = null; workerEndThread_evt = null; }
/// <summary> /// Turns this panel into multi-threaded mode. /// This will sort of glitch out other gdi things on the system, but at least its fast... /// </summary> public void ActivateThreaded() { ewh = new EventWaitHandle(false, EventResetMode.AutoReset); threadPaint = new Thread(PaintProc); threadPaint.IsBackground = true; threadPaint.Start(); }
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(); }
/// <summary> /// Creates the single instance. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public static bool IsFirstInstance(string name) { EventWaitHandle eventWaitHandle = null; string eventName = string.Format("{0}-{1}", Environment.MachineName, name); var isFirstInstance = false; try { // try opening existing wait handle eventWaitHandle = EventWaitHandle.OpenExisting(eventName); } catch { // got exception = handle wasn't created yet isFirstInstance = true; } if (isFirstInstance) { // init handle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName); // register wait handle for this instance (process) ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, WaitOrTimerCallback, null, Timeout.Infinite, false); eventWaitHandle.Close(); } return isFirstInstance; }
public SharedMemoryListener(IPCPeer peer) { _waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, EventName); _exit = false; _peer = peer; _lastSyncedVersion = null; }
public void SetUp() { server = new WebSocketServer(URI.Port); server.AddService<Echo>(URI.AbsolutePath); server.Start(); handle = new EventWaitHandle(false, EventResetMode.AutoReset); }
public void Dispose() { Kill(); if (_apps != null) { _apps.Dispose(); _apps = null; } if (_kill != null) { _kill.Dispose(); _kill = null; } }
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; } }
public HttpChannelListenerEntry (ChannelDispatcher channel, EventWaitHandle waitHandle) { ChannelDispatcher = channel; WaitHandle = waitHandle; ContextQueue = new Queue<HttpContextInfo> (); RetrieverLock = new object (); }
public Installer(string filename) { try { MsiFilename = filename; Task.Factory.StartNew(() => { // was coapp just installed by the bootstrapper? if (((AppDomain.CurrentDomain.GetData("COAPP_INSTALLED") as string) ?? "false").IsTrue()) { // we'd better make sure that the most recent version of the service is running. EngineServiceManager.InstallAndStartService(); } InstallTask = LoadPackageDetails(); }); bool wasCreated; var ewhSec = new EventWaitHandleSecurity(); ewhSec.AddAccessRule(new EventWaitHandleAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), EventWaitHandleRights.FullControl, AccessControlType.Allow)); _ping = new EventWaitHandle(false, EventResetMode.ManualReset, "BootstrapperPing", out wasCreated, ewhSec); // if we got this far, CoApp must be running. try { Application.ResourceAssembly = Assembly.GetExecutingAssembly(); } catch { } _window = new InstallerMainWindow(this); _window.ShowDialog(); if (Application.Current != null) { Application.Current.Shutdown(0); } ExitQuick(); } catch (Exception e) { DoError(InstallerFailureState.FailedToGetPackageDetails, e); } }
public Waiter(TimeSpan? interval = null) { _waitHandle = new AutoResetEvent(false); _timer = new System.Timers.Timer(); _timer.Elapsed += (sender, args) => _waitHandle.Set(); SetInterval(interval); }
private void EndProfile(RequestItem pending, IRestResponse response, EventWaitHandle signal) { TimeSpan elapsed = pending.Elapsed; network.Profile(response, pending.Started, elapsed); network.ProfilePendingRemove(pending); signal.Set(); }
public bool ForceOnce() { Process process = Process.GetProcessById(_processId); if (process == null || process.HasExited) throw new InvalidOperationException("Cannot force focus, process is not running"); _waitHandle = new AutoResetEvent(false); try { Win32.EnumWindowsProc ewc = CheckWindow; int focusedId = Win32.GetForegroundWindowPID(); if (focusedId != _processId) { _windowHandle = IntPtr.Zero; Win32.EnumerateWindows(ewc, IntPtr.Zero); bool waitResult = _waitHandle.WaitOne(5000, false); if (waitResult && _windowHandle != IntPtr.Zero) return Win32.SetForegroundWindow(_windowHandle, true); } } finally { _waitHandle.Close(); _waitHandle = null; } return false; }
public ThreadWorker (IScheduler sched, ThreadWorker[] others, IProducerConsumerCollection<Task> sharedWorkQueue, bool createThread, int maxStackSize, ThreadPriority priority, EventWaitHandle handle) { this.others = others; this.dDeque = new CyclicDeque<Task> (); this.sharedWorkQueue = sharedWorkQueue; this.workerLength = others.Length; this.isLocal = !createThread; this.waitHandle = handle; this.childWorkAdder = delegate (Task t) { dDeque.PushBottom (t); sched.PulseAll (); }; // Find the stealing start index randomly (then the traversal // will be done in Round-Robin fashion) do { this.stealingStart = r.Next(0, workerLength); } while (others[stealingStart] == this); InitializeUnderlyingThread (maxStackSize, priority); }
public void Start(EventWaitHandle startEventHandle) { Contract.Requires<ArgumentNullException>(startEventHandle != null, "startEventHandle"); if (!Active) { var waitHandle = new ManualResetEventSlim(false); lock (_listener) { _shuttingDown = false; _listener.Start(); _acceptSocketThread = new Thread(AcceptSocketLoop); _acceptSocketThread.Start(waitHandle); } waitHandle.Wait(); _logger.DebugFormat("started on {0}", LocalEndPoint); } startEventHandle.Set(); }
public override string ResolveToString() { if (!Parameters.Contains("url") || string.IsNullOrEmpty(Parameters["url"].ToString())) throw new InvalidOperationException(); string url = Parameters["url"].ToString(); string resultString = null; using (var wc = new WebClient()) { var tlock = new EventWaitHandle(false, EventResetMode.ManualReset); wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) => { // TODO: Add progress monitoring }); wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler((sender, e) => { resultString = e.Result; tlock.Set(); }); wc.DownloadStringAsync(new Uri(url)); tlock.WaitOne(); tlock.Dispose(); } return resultString; }
/// <summary> /// Constructor for a message with or without waiting mechanism /// </summary> /// <param name="action"></param> /// <param name="waitForInvocation">When true, the message creator requires a waiting mechanism</param> public Message(Action action, bool waitForInvocation) { this.m_action = action; if (waitForInvocation) this.m_waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); else this.m_waitHandle = null; }
internal ReadWriteExtractCallback(SevenZipSharedArchiveContext context) : base(context) { this.TerminateEvent = new ManualResetEvent(false); this.FinishedEvent = new ManualResetEvent(false); this.BeforeExtractItem = new AutoResetEvent(false); this.ConfirmExtractItem = new AutoResetEvent(false); }
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); } }
/// <summary> /// Fetches the Tf2 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 Schemazh FetchSchema() { var url = SchemaApiUrlBase; // 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 = Drop.SteamWeb.Request(url, "GET"); DateTime schemaLastModified = DateTime.Parse(response.Headers["Last-Modified"]); string result = GetSchemaString(response, schemaLastModified); response.Close(); // were done here. let others read. mre.Set(); SchemaResult schemaResult = JsonConvert.DeserializeObject<SchemaResult>(result); return schemaResult.result ?? null; }
public static bool CreateSingleInstance(string name, EventHandler<InstanceCallbackEventArgs> callback, string[] args) { string eventName = string.Format("{0}-{1}", Environment.MachineName, name); InstanceProxy.IsFirstInstance = false; InstanceProxy.CommandLineArgs = args; try { using (EventWaitHandle eventWaitHandle = EventWaitHandle.OpenExisting(eventName)) { UpdateRemoteObject(name); if (eventWaitHandle != null) eventWaitHandle.Set(); } Environment.Exit(0); } catch { InstanceProxy.IsFirstInstance = true; using (EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName)) { ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, WaitOrTimerCallback, callback, Timeout.Infinite, false); } RegisterRemoteType(name); } return InstanceProxy.IsFirstInstance; }
public override bool Execute() { try { syncEventName = new TaskItem(Guid.NewGuid().ToString()); handle = new EventWaitHandle(false, EventResetMode.ManualReset, syncEventName.ItemSpec); handle.Reset(); threadLock = GetLock(lockName); new Thread(new ThreadStart(AsyncExecute)).Start(); while (m_AsyncThreadState == ThreadState.NOT_STARTED) { Thread.Sleep(500); } return true; } catch (Exception e) { try { Log.LogErrorFromException(e); } catch { } return false; } }
bool TryInitialize() { try { _dte = SiteManager.GetGlobalService<DTE>(); _running = _dte != null; } catch { _running = false; } if (!_running) return false; // TODO: seen in the wild, _dte.Solution is null (?), need to schedule and restart initialization for those scenarios. _solution = new DteSolution(_dte.Solution); _solution.ProjectChanged += HandleProjectChange; var environment = ServiceLocator.GetService<IEnvironment>(); _packageManager = ServiceLocator.GetService<IPackageManager>(); _assembliesChanged = new EventWaitHandle(false, EventResetMode.AutoReset, System.Diagnostics.Process.GetCurrentProcess().Id + ASSEMBLY_NOTIFY); _rootDirectory = environment.DescriptorFile.Parent; _projectRepository = environment.ProjectRepository; RegisterFileListener(); RefreshProjects(); _timer = new Timer(_ => RefreshProjects(), null, Timeout.Infinite, Timeout.Infinite); return true; }
private void ThreadFunc() { try { EventWaitHandle[] handles = new EventWaitHandle[2]; handles[0] = new EventWaitHandle(false, EventResetMode.AutoReset, Common.Solution.HostKillerName(_name, "start")); handles[1] = new EventWaitHandle(false, EventResetMode.AutoReset, Common.Solution.HostKillerName(_name, "stop")); while (true) { int idx = EventWaitHandle.WaitAny(handles); switch (idx) { case 0: //start this.isActive = true; break; case 1: //stop this.isActive = false; if (host != null) { host.Abort(); host = null; Common.DomainManager.UnloadDomain(_name); } break; } } } catch(Exception) { } }
public ProcessIsolatedEnvironment(IDirectory baseDirectory) { _baseDirectory = baseDirectory; _environmentId = Guid.NewGuid().ToString(); _handle = new EventWaitHandle(false, EventResetMode.AutoReset, _environmentId); _hostProcess = CreateProcess(_environmentId); }
public void LoadUserData(IList <Uri> addresses, bool IsTruncateTempDB = true) { WebHttpCrawlerClient client = new WebHttpCrawlerClient(); client.SetRequestDetail = (x) => { x._HttpWebRequest.AutomaticDecompression = DecompressionMethods.GZip; x._HttpWebRequest.Referer = "https://api.stackexchange.com/docs/users"; }; WebThreadDesigation t = new WebThreadDesigation(client); t.EventWaitHandleName = "WebThreadDesigation"; StackoverflowPageAnalysis ana = new StackoverflowPageAnalysis(); AnalysisThreadDesigation <UserInfo> a = new AnalysisThreadDesigation <UserInfo>(ana); a.EventWaitHandleName = "StackoverflowPageAnalysis"; DBThreadDesigation d = new DBThreadDesigation(); d.EventWaitHandleName = "DBThreadDesigation"; CrawlerSyncObject syscobject = new CrawlerSyncObject(); AnalysisSyncObject anasissyncObject = new AnalysisSyncObject(); SendImformation infos = new SendImformation(); infos.ConnectString = "data source=CIA-SH-svr-sis;initial catalog=stackoverflowNew;integrated security=True;"; //infos.EventhandlerName = "dbo.SuggestionStagging"; //infos.DestinationtableName = "dbo.SuggestionStagging"; infos.EventhandlerName = "UserTemp1_Tinct"; infos.DestinationtableName = "UserTemp1_Tinct"; infos.IsWantToMerged = false; infos.MergeSQlSPName = ""; EventWaitHandle eventWaitHandle1 = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, t.EventWaitHandleName); eventWaitHandle1.Reset(); EventWaitHandle eventWaitHandle2 = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, a.EventWaitHandleName); eventWaitHandle2.Reset(); EventWaitHandle eventWaitHandle3 = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, d.EventWaitHandleName); eventWaitHandle3.Reset(); EventWaitHandle eventWaitHandle4 = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, infos.EventhandlerName); eventWaitHandle4.Reset(); Task.Run(() => { t.CrawlerUris(addresses, 10, syscobject); }); Task.Run(() => { a.AnalysisResults(t.resultlists, 5, syscobject, anasissyncObject); }); Task.Run(() => { d.SendDispatchDatas <UserInfo>(ref a.datas, 500, ref anasissyncObject, infos, null); }); eventWaitHandle1.WaitOne(); eventWaitHandle2.WaitOne(); eventWaitHandle3.WaitOne(); eventWaitHandle4.WaitOne(); }
public MatlabExecutionEngine(string path) { Path = path; matlabApp = null; matlabProcess = null; owningProcess = false; eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); }
public Model() { timer = new System.Timers.Timer(randValue(Library.Settings.Instance.TimerInterval, 15)); timer.Elapsed += new System.Timers.ElapsedEventHandler(onTimer); needToContinue = true; waiter = new EventWaitHandle(true, System.Threading.EventResetMode.AutoReset, Library.Settings.Instance.WaitEventName); }
public override void Initialize() { this.error = null; this.cancelled = false; this.connected = false; this.timedOut = false; this.target = new RasDialer(); this.target.PhoneBookPath = phonebookPath; this.target.DialCompleted += new EventHandler <DialCompletedEventArgs>(this.Target_DialCompleted); this.target.Error += new EventHandler <System.IO.ErrorEventArgs>(this.Target_Error); this.target.StateChanged += new EventHandler <StateChangedEventArgs>(this.Target_StateChanged); this.stateWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); this.waitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset); base.Initialize(); }
internal DevicePickerControl(DevicePicker picker, Popup popup) { _owner = picker; _popup = popup; _popup.Closed += _popup_Closed; _handle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset); this.Resources.Add("AccentBrush", new SolidColorBrush(this._owner.Appearance.AccentColor)); this.Resources.Add("ForegroundBrush", new SolidColorBrush(this._owner.Appearance.ForegroundColor)); this.Resources.Add("SelectedAccentBrush", new SolidColorBrush(this._owner.Appearance.SelectedAccentColor)); this.Resources.Add("SelectedBackgroundBrush", new SolidColorBrush(this._owner.Appearance.SelectedBackgroundColor)); this.Resources.Add("SelectedForegroundBrush", new SolidColorBrush(this._owner.Appearance.SelectedForegroundColor)); this.InitializeComponent(); RootVisual.Background = new SolidColorBrush(this._owner.Appearance.BackgroundColor); this.Foreground = new SolidColorBrush(this._owner.Appearance.ForegroundColor); this.Loaded += DevicePickerControl_Loaded; }
public static void Initialize() { Program.AssertOffEventThread(); Thread thread; string evname; EventWaitHandleSecurity evsec; EventWaitHandleAccessRule evrule; string user; xgs = Program.GetXGS(); systray = Program.GetSystray(); alertList = Program.GetAlertList(); evname = xgs.GetAlertsEventName(); user = Environment.UserDomainName + "\\" + Environment.UserName; evalerts = EventWaitHandle.OpenExisting(evname, EventWaitHandleRights.ReadPermissions | EventWaitHandleRights.ChangePermissions); evsec = evalerts.GetAccessControl(); evrule = new EventWaitHandleAccessRule(user, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, AccessControlType.Deny); evsec.RemoveAccessRule(evrule); evrule = new EventWaitHandleAccessRule(user, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, AccessControlType.Allow); evsec.AddAccessRule(evrule); evalerts.SetAccessControl(evsec); evalerts = EventWaitHandle.OpenExisting(evname); thread = new Thread(alertUpdater); thread.Name = "XenClient Alert Thread"; thread.IsBackground = true; thread.Start(); }
public static void Initialize(XenGuestAgentLib.XenGuestServices service) { Program.AssertOffEventThread(); Thread thread; string evname; EventWaitHandleSecurity evsec; EventWaitHandleAccessRule evrule; string user; xgsc = service; evname = xgsc.RegisterVmsEvent(); user = Environment.UserDomainName + "\\" + Environment.UserName; evvms = EventWaitHandle.OpenExisting(evname, EventWaitHandleRights.ReadPermissions | EventWaitHandleRights.ChangePermissions); evsec = evvms.GetAccessControl(); evrule = new EventWaitHandleAccessRule(user, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, AccessControlType.Deny); evsec.RemoveAccessRule(evrule); evrule = new EventWaitHandleAccessRule(user, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, AccessControlType.Allow); evsec.AddAccessRule(evrule); evvms.SetAccessControl(evsec); evvms = EventWaitHandle.OpenExisting(evname); // Start the monitor thread thread = new Thread(CacheXgsMonitor); thread.Name = "XenClient Cache Thread"; thread.IsBackground = true; thread.Start(); }
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"); } }
public static bool TryOpenExisting(string name, EventWaitHandleRights rights, out EventWaitHandle result) { throw new NotSupportedException(); }
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"); } }
public static EventWaitHandleSecurity GetAccessControl(EventWaitHandle handle) { return(handle.GetAccessControl()); }
public static void SetAccessControl(EventWaitHandle handle, EventWaitHandleSecurity eventSecurity) { handle.SetAccessControl(eventSecurity); }
static OpenExistingResult OpenExistingWorker(string name, out EventWaitHandle result) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); }
static void Main(string[] args) { System.Configuration.Install.InstallContext _args = new System.Configuration.Install.InstallContext(null, args); if (_args.IsParameterTrue("debug")) { System.Console.WriteLine("Wait for debugger, press any key to continue..."); System.Console.ReadKey(); } 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.Threading.EventWaitHandle e = null; if (_args.IsParameterTrue("start-service")) { // start service try { e = System.Threading.EventWaitHandle.OpenExisting(androidServer_Event_Name); e.Close(); logIt("Instance already started."); } catch (WaitHandleCannotBeOpenedException) { e = new EventWaitHandle(false, EventResetMode.ManualReset, androidServer_Event_Name); //argMap.Add("quitEvent", e); SerialManager.Init(); start(args, e); e.Close(); } catch (Exception) { } } else if (_args.IsParameterTrue("kill-service")) { // stop service try { e = System.Threading.EventWaitHandle.OpenExisting(androidServer_Event_Name); if (e != null) { e.Set(); } } catch (Exception) { } } else { System.Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name); System.Console.WriteLine("-start-service: to start the service"); System.Console.WriteLine("-kill-service: to stop the service"); } // SerialManager serialManager = new SerialManager(); // serialManager.Init(); }
private static OpenExistingResult OpenExistingWorker(string name, EventWaitHandleRights rights, out EventWaitHandle result) { #if PLATFORM_WINDOWS if (name == null) { throw new ArgumentNullException(nameof(name)); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); } result = null; SafeWaitHandle myHandle = Win32Native.OpenEvent(AccessRights, false, name); if (myHandle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); if (Interop.Errors.ERROR_FILE_NOT_FOUND == errorCode || Interop.Errors.ERROR_INVALID_NAME == errorCode) { return(OpenExistingResult.NameNotFound); } if (Interop.Errors.ERROR_PATH_NOT_FOUND == errorCode) { return(OpenExistingResult.PathNotFound); } if (null != name && 0 != name.Length && Interop.Errors.ERROR_INVALID_HANDLE == errorCode) { return(OpenExistingResult.NameInvalid); } //this is for passed through Win32Native Errors throw Win32Marshal.GetExceptionForWin32Error(errorCode, ""); } result = new EventWaitHandle(myHandle); return(OpenExistingResult.Success); #else throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); #endif }
public byte[] ReadUSB() { // try reading a few times, in case we lose the connection brieflyl for (int tries = 0; tries < 3; ++tries) { // set up a non-blocking ("overlapped") read const int rptLen = 15; byte[] buf = new byte[rptLen]; buf[0] = 0x00; EventWaitHandle ev = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset); ov.OffsetLow = ov.OffsetHigh = 0; ov.EventHandle = ev.SafeWaitHandle.DangerousGetHandle(); HIDImports.ReadFile(fp, buf, rptLen, IntPtr.Zero, ref ov); // Wait briefly for the read to complete. But don't wait forever - we might // be talking to a device interface that doesn't provide the type of status // report we're looking for, in which case we don't want to get stuck waiting // for something that will never happen. If this is indeed the controller // interface we're interested in, it will respond within a few milliseconds // with our status report. if (ev.WaitOne(100)) { // The read completed successfully! Get the result. UInt32 readLen; if (HIDImports.GetOverlappedResult(fp, ref ov, out readLen, 0) == 0) { // The read failed. Try re-opening the file handle in case we // dropped the connection, then re-try the whole read. TryReopenHandle(); continue; } else if (readLen != rptLen) { // The read length didn't match what we expected. This might be // a different device (not a Pinscape controller) or a different // version that we don't know how to talk to. In either case, // return failure. return(null); } else { // The read succeed and was the correct size. Return the data. return(buf); } } else { // The read timed out. This must not be our control interface after // all. Cancel the read and try reopening the handle. HIDImports.CancelIo(fp); if (TryReopenHandle()) { continue; } return(null); } } // don't retry more than a few times return(null); }
public ThreadPoolHandler(HandleThread handler, System.Collections.ICollection collection, System.Threading.EventWaitHandle mre) { this.eventWaitHandle = mre; this.collection = collection; this.handler = handler; }
public static bool TryOpenExisting(string name, out EventWaitHandle result) { return(OpenExistingWorker(name, (EventWaitHandleRights)0, out result) == OpenExistingResult.Success); }
public static bool TryOpenExisting(string name, out EventWaitHandle result) { return(TryOpenExisting( name, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, out result)); }