我怎么能执行一个非阻塞System.Beep()? [英] How can I execute a non-blocking System.Beep()?
问题描述
在C#中,我可以执行Console.Beep()。但是,如果你指定的说1000,或1秒的时间,也不会执行的code中的下一行,直到第二遍。
In C# I can perform a Console.Beep(). However, if you specify a duration of say 1000, or 1 second, it will not execute the next line of code until that second passes.
有没有什么办法可以在非阻塞的方式执行Console.Beep(),所以它会继续发出蜂鸣声,仍然继续执行其下的code,同时发出蜂鸣音?
Is there any way possible to execute Console.Beep() in a non-blocking fashion so it will continue to beep and still continue executing the code below it while beeping?
推荐答案
您可以在一个单独的线程中运行它。
You can run it in a separate thread.
new Thread(() => Console.Beep()).Start();
今天早上我醒来发现对这个答案的评论乱舞。所以,我以为我会附和一些其他的想法。
I woke this morning to find flurry of comments on this answer. So I thought I would chime in with some other ideas.
上面也可以实现其上运行的线程池的螺纹,通过使用以下
The above can also be achieved running the thread on the Thread Pool, by using the following.
Action beep = Console.Beep;
beep.BeginInvoke((a) => { beep.EndInvoke(a); }, null);
在上面的code最重要的是,如果你使用的BeginInvoke否则你会遇到内存泄漏调用EndInvoke会在你的委托。
The important thing in the above code is to call EndInvoke on your delegate if you use BeginInvoke otherwise you will experience memory leaks.
从MSDN:重要:总是调用EndInvoke来完成你的异步调用。 <一href="http://msdn.microsoft.com/en-us/library/2e08f6yc(VS.80).aspx">http://msdn.microsoft.com/en-us/library/2e08f6yc(VS.80).aspx
From MSDN:Important: Always call EndInvoke to complete your asynchronous call. http://msdn.microsoft.com/en-us/library/2e08f6yc(VS.80).aspx
另外,也可以使用专用的蜂鸣声线有蜂鸣声在后台运行时,在无需创建一个新的线程,每次或使用线程池的需求(见西蒙·查德威克的评论)。举一个简单的例子,你可以有以下几种。请注意,我通过1作为maxStackSize,这将确保最低(而不是1,最小值)堆栈空间致力于此线程,请参阅MSDN的更多细节这一点。
Alternatively, you can use the dedicated Beep thread to have beeps run in the background when on demand without creating a new thread everytime or using the thread pool (see Simon Chadwick's comment). As a simple example, you could have the following. Notice that I pass 1 as the maxStackSize, this will ensure that the minimum (not 1, minimum) stack space is committed for this thread, see MSDN for more detail on this.
class BackgroundBeep
{
static Thread _beepThread;
static AutoResetEvent _signalBeep;
static BackgroundBeep()
{
_signalBeep = new AutoResetEvent(false);
_beepThread = new Thread(() =>
{
for (; ; )
{
_signalBeep.WaitOne();
Console.Beep();
}
}, 1);
_beepThread.IsBackground = true;
_beepThread.Start();
}
public static void Beep()
{
_signalBeep.Set();
}
}
通过这一点,所有你需要做的,随时与出创建新线程运行的底色蜂鸣音进行下面的调用
With this, all you need to do to run a backround beep at anytime with out creating new threads is make the following call
BackgroundBeep.Beep();
这篇关于我怎么能执行一个非阻塞System.Beep()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!