以下代码的缺点是,在主线程重置waithandle之后,工作线程既不会立即终止也不会执行最终操作.相反,它将继续执行它正在进行的操作,直到它到达循环的下一次迭代,此时它将无限期地被阻塞.
static void Main()
{
ManualResetEvent m = new ManualResetEvent(true); // or bool b = true
Thread thread = new Thread(new ThreadStart(delegate()
{
while(m.WaitOne()) //or while(b)
{
//do something
}
//perform final operation and exit
}));
thread.Start();
//do something
m.Reset(); //or b = false
//do something else
}
Run Code Online (Sandbox Code Playgroud)
下面的代码有一个缺点,它使用Abort()方法(有人说它应该不惜一切代价避免),但完全正是我正在寻找的:强制工作线程突破循环主线程告诉它这样做,执行最后一个操作,然后退出.
static void Main()
{
Thread thread = new Thread(new ThreadStart(delegate()
{
try
{
while(true)
{
//do something
}
}
catch(ThreadAbortException e)
{
//perform final operation and exit
}
}));
thread.Start();
//do …Run Code Online (Sandbox Code Playgroud) 我有
try
{
using (var eventWaitHandle = EventWaitHandle.OpenExisting(name))
{
eventWaitHandle.Set();
}
Environment.Exit(0);
}
catch(WaitHandleCannotBeOpenedException)
{
// register new handle code goes here
}
Run Code Online (Sandbox Code Playgroud)
没有抛出/处理异常,有没有办法做到这一点?
我只是好奇,对系统范围的命名有任何限制EventWaitHandle吗?我想使用一个URL作为一个的名称,但它可能有很多奇怪的字符,我不希望它默默地失败或其他一些,所以只要在这里检查是否有任何已知的非法字符这些的名字.
我自己试着找到这个,但是我的google-fu并不适合鼻烟.
我正在玩AutoResetEvent,我的应用程序没有结束,我想我知道原因:线程仍在运行,因此应用程序不会终止.通常,在Main()我按下一个键后,应用程序终止.但控制台窗口不再关闭.我有一个简单的控制台应用:
private static EventWaitHandle waitHandle = new AutoResetEvent(false);
static void Main(string[] args)
{
AutoResetEventFun();
Console.WriteLine("Press any key to end.");
Console.ReadKey();
waitHandle.Close(); // This didn't cause the app to terminate.
waitHandle.Dispose(); // Nor did this.
}
private static void AutoResetEventFun()
{
// Start all of our threads.
new Thread(ThreadMethod1).Start();
new Thread(ThreadMethod2).Start();
new Thread(ThreadMethod3).Start();
new Thread(ThreadMethod4).Start();
while (Console.ReadKey().Key != ConsoleKey.X)
{
waitHandle.Set(); // Let one of our threads process.
}
}
// There are four of these methods. …Run Code Online (Sandbox Code Playgroud)