本文整理汇总了C#中System.Threading.EventWaitHandle.Close方法的典型用法代码示例。如果您正苦于以下问题:C# EventWaitHandle.Close方法的具体用法?C# EventWaitHandle.Close怎么用?C# EventWaitHandle.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.EventWaitHandle
的用法示例。
在下文中一共展示了EventWaitHandle.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ForceOnce
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;
}
示例2: IsFirstInstance
/// <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;
}
示例3: Main
private static void Main(string[] args)
{
//Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("he");
if (args.Any(s => (s == "driverinstall") || (s == "-driverinstall")))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new WelcomeDialog());
return;
}
GCSettings.LatencyMode = GCLatencyMode.LowLatency;
try
{
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
}
catch
{
// Ignore problems raising the priority.
}
try
{
// another instance is already running if OpenExsting succeeds.
threadComEvent = EventWaitHandle.OpenExisting(singleAppComEventName);
threadComEvent.Set(); // signal the other instance.
threadComEvent.Close();
return; // return immediatly.
}
catch
{
/* don't care about errors */
}
// Create the Event handle
threadComEvent = new EventWaitHandle(false, EventResetMode.AutoReset, singleAppComEventName);
CreateInterAppComThread();
if (mutex.WaitOne(TimeSpan.Zero, true))
{
RootHub = new ControlService();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new DS4Form(args));
mutex.ReleaseMutex();
}
// End the communication thread.
singleAppComThread.CancelAsync();
while (singleAppComThread.IsBusy)
{
Thread.Sleep(50);
}
threadComEvent.Close();
}
示例4: CreateSingleInstance
/// <summary>
/// Creates the single instance.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="callback">The callback.</param>
/// <returns></returns>
public static bool CreateSingleInstance(string name, String[] args,
EventHandler<InstanceCallbackEventArgs> callback)
{
Logger.LogDebug("Workbench", 1, "Creating single instance setup\n");
EventWaitHandle eventWaitHandle = null;
string eventName = String.Format("{0}.{1}.{2}", Environment.MachineName, Environment.UserName, name);
InstanceProxy.IsFirstInstance = false;
InstanceProxy.CommandLineArgs = args;
try
{
// Try opening existing wait handle.
Logger.LogDebug("Workbench", 2, "Trying to open existing event wait handle\n");
eventWaitHandle = EventWaitHandle.OpenExisting(eventName);
}
catch
{
// Got exception => handle wasn't created yet.
InstanceProxy.IsFirstInstance = true;
}
if (InstanceProxy.IsFirstInstance)
{
Logger.LogDebug("Workbench", 2, "This is the first application instance\n");
// Since this is the first instance we need to set up our communication infrastructure.
eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName);
ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, WaitOrTimerCallback, callback,
Timeout.Infinite, false);
eventWaitHandle.Close();
// Register shared type (used to pass data between processes).
RegisterRemoteType(name);
}
else
{
Logger.LogDebug("Workbench", 2, "Another application instance is already running\n");
// We are second in a row, so pass application arguments to the shared object and quit.
UpdateRemoteObject(name);
if (eventWaitHandle != null)
eventWaitHandle.Set();
}
return InstanceProxy.IsFirstInstance;
}
示例5: Make
internal static void Make(String name, Application app)
{
EventWaitHandle eventWaitHandle = null;
String eventName = Environment.MachineName + "-" + name;
bool isFirstInstance = false;
try
{
eventWaitHandle = EventWaitHandle.OpenExisting(eventName);
}
catch
{
// it's first instance
isFirstInstance = true;
}
if (isFirstInstance)
{
eventWaitHandle = new EventWaitHandle(
false,
EventResetMode.AutoReset,
eventName);
ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, waitOrTimerCallback, app, Timeout.Infinite, false);
// not need more
eventWaitHandle.Close();
// !!! delete it if not use
setFirstArgs();
}
else
{
// !!! delete it if not use
setArgs();
eventWaitHandle.Set();
// For that exit no interceptions
Environment.Exit(0);
}
}
示例6: CreateSingleInstance
/// <summary>
/// Creates the single instance.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="callback">The callback.</param>
/// <returns></returns>
public static bool CreateSingleInstance(string name, EventHandler<InstanceCallbackEventArgs> callback)
{
EventWaitHandle eventWaitHandle = null;
string eventName = string.Format("{0}-{1}", Environment.MachineName, name);
InstanceProxy.IsFirstInstance = false;
InstanceProxy.CommandLineArgs = Environment.GetCommandLineArgs();
try
{
// try opening existing wait handle
eventWaitHandle = EventWaitHandle.OpenExisting(eventName);
}
catch
{
// got exception = handle wasn't created yet
InstanceProxy.IsFirstInstance = true;
}
if (InstanceProxy.IsFirstInstance)
{
// init handle
eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName);
// register wait handle for this instance (process)
ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, WaitOrTimerCallback, callback, Timeout.Infinite, false);
eventWaitHandle.Close();
// register shared type (used to pass data between processes)
RegisterRemoteType(name);
}
else
{
// pass console arguments to shared object
UpdateRemoteObject(name);
// invoke (signal) wait handle on other process
if (eventWaitHandle != null) eventWaitHandle.Set();
// kill current process
Environment.Exit(0);
}
return InstanceProxy.IsFirstInstance;
}
示例7: CheckForOtherApp
/// <summary>
///
/// </summary>
/// <param name="uniqueName"></param>
/// <returns>True is another instance is already running. False otherwise</returns>
public static Boolean CheckForOtherApp(String uniqueName)
{
SingleAppComEventName = uniqueName;
try
{
// another instance is already running
threadComEvent = EventWaitHandle.OpenExisting(SingleAppComEventName);
threadComEvent.Set(); // signal the other instance.
threadComEvent.Close();
return true; // return immediatly.
}
catch { /* don't care about errors */ }
// Create the Event handle
threadComEvent = new EventWaitHandle(false, EventResetMode.AutoReset, SingleAppComEventName);
// make sure the resources are cleaned up afterwards.
cleanupCode = new CleanupCode();
CreateInterAppComThread();
return false;
}
示例8: ActivatorHost
public ActivatorHost(string guid, int processId, ProcessDomainSetup setup)
{
SetupDllDirectories(setup);
var serverProvider = new BinaryServerFormatterSinkProvider { TypeFilterLevel = setup.TypeFilterLevel };
var clientProvider = new BinaryClientFormatterSinkProvider();
_process = Process.GetProcessById(processId);
var properties = new Hashtable();
properties["portName"] = string.Format(ServerChannelName, guid);
properties["name"] = string.Format(ServerChannelName, guid);
properties["rejectRemoteRequests"] = true;
setup.Remoting.ApplyServerProperties(properties);
_channel = new IpcChannel(properties, clientProvider, serverProvider);
ChannelServices.RegisterChannel(_channel, false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Activator), ActivatorName, WellKnownObjectMode.Singleton);
EventWaitHandle serverStartedHandle = null;
try
{
bool created;
serverStartedHandle = new EventWaitHandle(false, EventResetMode.ManualReset, string.Format(EventName, guid), out created);
if (created)
{
throw new Exception("Event handle did not exist for remote process");
}
serverStartedHandle.Set();
}
finally
{
if (serverStartedHandle != null)
{
serverStartedHandle.Close();
}
}
}
示例9: TestElection
public void TestElection()
{
testName = "TestElection";
testHome = testFixtureHome + "/" + testName;
client1StartSignal = new AutoResetEvent(false);
client2StartSignal = new AutoResetEvent(false);
client1ReadySignal = new AutoResetEvent(false);
client2ReadySignal = new AutoResetEvent(false);
client3StartSignal = new AutoResetEvent(false);
client3ReadySignal = new AutoResetEvent(false);
masterLeaveSignal = new AutoResetEvent(false);
Thread thread1 = new Thread(
new ThreadStart(UnstableMaster));
Thread thread2 = new Thread(
new ThreadStart(StableClient1));
Thread thread3 = new Thread(
new ThreadStart(StableClient2));
Thread thread4 = new Thread(
new ThreadStart(StableClient3));
thread1.Start();
Thread.Sleep(1000);
thread2.Start();
thread3.Start();
thread4.Start();
thread4.Join();
thread3.Join();
thread2.Join();
thread1.Join();
client1StartSignal.Close();
client2StartSignal.Close();
client1ReadySignal.Close();
client2ReadySignal.Close();
client3ReadySignal.Close();
client3StartSignal.Close();
masterLeaveSignal.Close();
}
示例10: btnGetStats_Click
private void btnGetStats_Click(object sender, EventArgs e)
{
if(_active_servo == null)
{
MsgBox.Show(this, "Select a Node");
return;
}
// Uncheck 'Show Stored Statistics' radio button
suppress_stored_plot_checkbox = true;
cbxShowStatsPrev.Checked = false;
suppress_stored_plot_checkbox = false;
_statistics_ev = new AutoResetEvent(false);
Graphics g = picbxStats.CreateGraphics();
try
{
if(_active_servo.ServoSlave.StatsRead(GetStatistics_callback))
{
g.Clear(System.Drawing.Color.White);
g.DrawString("Wait for Statistics", new Font("Verdana", 14),
new SolidBrush(Color.Black), 10, 10);
if(_statistics_ev.WaitOne(15000, false) == false)
{
MsgBox.Show(this, "Stats timeout\n");
g.Clear(System.Drawing.Color.White);
_statistics_ev.Close();
_statistics_ev = null;
return;
}
}
}
catch(Exception error)
{
MsgBox.Show(this, error.ToString());
Log(LogMsgType.Error, error.ToString() + "\n");
}
_statistics_ev.Close();
_statistics_ev = null;
ClrText(tbxStats);
if(_active_servo.ServoSlave.StatBuf == null)
{
MsgBox.Show(this, "StatBuf is null!");
return;
}
if(_active_servo.ServoSlave.StatBuf.Count > 0)
{
// We've got valid stats data - copy stats buffer to StatsCur
_active_servo.StatsCur = _active_servo.ServoSlave.StatBuf;
// Build control points from mem funcs
_active_servo.CtlPtsCur.Clear();
if(cbxMemFuncCtlPts.Checked)
{
// Derive PosErr Ctl points from bytes 4 and 1 of PosMembershipFunctionArray
_active_servo.CtlPtsCur.Add(_active_servo.ServoSlave.PosMemFuncArray[4]);
_active_servo.CtlPtsCur.Add(_active_servo.ServoSlave.PosMemFuncArray[1]);
// Derive Change Ctl points from bytes 4 and 1 of SpdMembershipFunctionArray
_active_servo.CtlPtsCur.Add(_active_servo.ServoSlave.SpdMemFuncArray[4]);
_active_servo.CtlPtsCur.Add(_active_servo.ServoSlave.SpdMemFuncArray[1]);
// Derive Output Ctl points from bytes 0 and 1 of OutSingletonArray
_active_servo.CtlPtsCur.Add(_active_servo.ServoSlave.OutSingletonArray[0]);
_active_servo.CtlPtsCur.Add(_active_servo.ServoSlave.OutSingletonArray[1]);
}
else
{
_active_servo.CtlPtsCur.Clear();
}
}
else
{
g.Clear(System.Drawing.Color.White);
Log(LogMsgType.Warning, "Statistics Buffer empty - initiate a move to fill\n");
MsgBox.Show(this, "Statistics Buffer empty - initiate a move to fill");
return;
}
// Build text box output
StringBuilder sb = new StringBuilder();
foreach(StatStruct stat in _active_servo.StatsCur)
{
sb.Append(stat.err.ToString("X2") + " ");
sb.Append(stat.change.ToString("X2") + " ");
sb.Append(stat.duty.ToString("X2") + "\r\n");
}
SetText(tbxStats, sb.ToString());
plotData(_active_servo);
g.Dispose();
}
示例11: RunThread
void RunThread()
{
var canRun = true;
var e = KeyEvent.Empty;
var inputEvent = new EventWaitHandle(false, EventResetMode.AutoReset, inputEventName);
try
{
OnActivated();
}
catch (Exception ex)
{
canRun = false;
OnScriptError(ex);
}
canRun = BeforeRunThread();
while (IsRunning)
{
if (canRun)
{
for (e = GetKeyEvent(); e.IsEmpty == false; e = GetKeyEvent())
{
OnKeyEvent(e);
if (!IsRunning)
{
break;
}
}
}
inputEvent.WaitOne();
}
//ClearKeyEvents();
SetBacklightColor(128, 255, 255);
lcd.RemoveFromFront();
inputEvent.Close();
AfterRunThread();
var inputExit = new EventWaitHandle(false, EventResetMode.AutoReset, inputExitName);
inputExit.Set();
inputExit.Close();
}
示例12: CreateAddInProcess
private Process CreateAddInProcess()
{
Process addInProcess = new Process();
Guid guid = Guid.NewGuid();
String args = String.Format(CultureInfo.InvariantCulture, "/guid:{0} /pid:{1}", guid, Process.GetCurrentProcess().Id);
addInProcess.StartInfo.CreateNoWindow = true;
addInProcess.StartInfo.UseShellExecute = false;
addInProcess.StartInfo.Arguments = args;
addInProcess.StartInfo.FileName = _pathToAddInProcess;
#if _DEBUG
String debuggerPath = Environment.GetEnvironmentVariable("COMPLUS_AddInProcessDebugger");
String debuggerArgs = Environment.GetEnvironmentVariable("COMPLUS_AddInProcessDebuggerArgs");
if(!String.IsNullOrEmpty(debuggerPath))
{
addInProcess.StartInfo.Arguments = "";
if(!String.IsNullOrEmpty(debuggerArgs))
{
addInProcess.StartInfo.Arguments = debuggerArgs + " ";
}
addInProcess.StartInfo.Arguments += _pathToAddInProcess + " " + args;
addInProcess.StartInfo.FileName = debuggerPath;
}
#endif
// wait until it's ready
EventWaitHandle readyEvent = new EventWaitHandle(false, EventResetMode.ManualReset, "AddInProcess:" + guid);
addInProcess.Start();
bool success = readyEvent.WaitOne(_startupTimeout, false);
readyEvent.Close();
if (!success) {
// Here's an effort to avoid leaving a half-baked process around if possible.
try {
addInProcess.Kill();
}
catch (Exception) {}
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Res.CouldNotCreateAddInProcess, _startupTimeout.ToString()));
}
_guid = guid;
return addInProcess;
}
示例13: CreateSubmitWorkerThread
// Create a new wait handle identified by the prSearchKey and wait for the
// Workshare.SendLink.Client.exe to signal it after the upload has completed.
private void CreateSubmitWorkerThread(string prSearchKey)
{
Logger.LogInfo("SendLink deterministic send waiting for upload to complete. PrSearchKey = " + prSearchKey);
var submitMessage = new Thread(new ThreadStart(delegate
{
var eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, prSearchKey);
_submitWaitHandles.Add(eventWaitHandle);
eventWaitHandle.WaitOne();
Logger.LogInfo("SendLink deterministic send notified upload complete and mail can be submited. PrSearchKey = " + prSearchKey);
if (_disposing)
{
return;
}
lock (_lock)
{
SubmitNonDeferredItems();
}
_submitWaitHandles.Remove(eventWaitHandle);
eventWaitHandle.Close();
}));
submitMessage.Start();
}
示例14: listenUsingNamedEventsAndMemoryMappedFiles
private void listenUsingNamedEventsAndMemoryMappedFiles()
{
if (m_NamedEventHandle == null)
{
EventLog.WriteEntry("Application",
string.Format(
"IpcService::listenUsingNamedEventsAndMemoryMappedFiles: NULL event"),
EventLogEntryType.Error);
return;
}
if (m_NamedEventBuddyHandle == null)
{
EventLog.WriteEntry("IpcService",
string.Format("IpcService::listenUsingNamedEventsAndMemoryMappedFiles: NULL event (Buddy)"),
EventLogEntryType.Error);
return;
}
m_Terminated = new EventWaitHandle(false, EventResetMode.ManualReset);
EventWaitHandle[] waitObjects =
new EventWaitHandle[] { m_Terminated, m_NamedEventHandle };
try
{
while(true)
{
//Waits on "Ready to read?"
int index = EventWaitHandle.WaitAny(waitObjects,
Timeout.Infinite,false);
if (index == 0)
{
break;
}
try
{
//Read data
string data = Peek();
if (IpcEvent != null)
{
IpcEvent(this, new TextualEventArgs(data));
}
}
catch(Exception ex)
{
EventLog.WriteEntry("IpcService",
string.Format("IpcService::listenUsingNamedEventsAndMemoryMappedFiles: Error: {0}", ex),
EventLogEntryType.Error);
}
finally
{
m_NamedEventHandle.Reset();
//Signals "Read done"
m_NamedEventBuddyHandle.Set();
}
}
}
finally
{
if (m_NamedEventHandle != null)
{
m_NamedEventHandle.Set();
m_NamedEventHandle.Close();
}
if (m_NamedEventBuddyHandle != null)
{
m_NamedEventBuddyHandle.Set();
m_NamedEventBuddyHandle.Close();
}
m_Terminated.Close();
}
}
示例15: ReserveNextAvailableNodeNumber
/// <summary>
/// This function attempts to find out a node number for which
/// the event named Node_x_ProviderMutex doesn't exist. The existance
/// of the event indicates that some other node provider is using the node.
/// </summary>
private void ReserveNextAvailableNodeNumber(int currentNodeNumber)
{
while (nodeReserveHandle == null)
{
bool createdNew = false;
nodeReserveHandle =
new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeReserveEventName(currentNodeNumber), out createdNew);
if (!createdNew)
{
nodeReserveHandle.Close();
nodeReserveHandle = null;
currentNodeNumber++;
}
else
{
nodeNumber = currentNodeNumber;
// Create the shared memory resources
if (!CreateSharedMemoryBuffers())
{
nodeReserveHandle.Close();
nodeReserveHandle = null;
currentNodeNumber++;
}
}
}
}