110,549
社区成员
发帖
与我相关
我的任务
分享
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Thread playsound; //播放声音的线程
readonly ConcurrentQueue<bool> alarmQueue=new ConcurrentQueue<bool>();//线程安全的并发队列,多个线程访问不会出错
void main()
{
//------------------------------------主程序----------------------------------------------------------
while(true)
{
// ……
// if(检测到目标)
alarmQueue.Enqueue(true); //加入队列
showAlarm();
}
//----------------------------------------------------------------------------------------------
}
private void showAlarm() //启动线程
{
bool bPlay = false;
if (alarmQueue.TryDequeue(out bPlay))//从队列里提取 ,如果队列里没有,就不会创建线程播放声音
{
if (bPlay)
{
//playsound = new Thread(new ThreadStart(PlaySound));//建议不要用线程,开销太大
//playsound.Start();
Task.Factory.StartNew(PlaySound);//用这个,开销小
}
}
}
private void PlaySound() //播放声音方法
{
string path = "warning.wav";
System.Media.SoundPlayer player = new System.Media.SoundPlayer(path);
player.Play();
}
}
}