我是線程新手,需要很多幫助。 我有基於啓動線程的事件的代碼。問題是我鬆散對線程和thread.abort()的引用;不會阻止它,因此我的應用程序不會停止。謝謝重新啓動正在運行的線程
using System;
using Gtk;
using NAudio;
using NAudio.Wave;
using System.Threading;
public class Trackbox {
public static Thread thread;
public static void Main() {
Application.Init();
//Create the Window
Window myWin = new Window("Trackbox");
myWin.SetIconFromFile("Assets//logo.png");
myWin.Resize(200, 100);
Button playButton = new Button("Play Sound");
playButton.Clicked += new EventHandler(playWav);
myWin.Add(playButton);
myWin.DeleteEvent += delegate { exitTrackbox(); };
//Show Everything
myWin.ShowAll();
Application.Run();
}
private static void exitTrackbox() {
//Doesn't kill the application
thread.Abort();
Application.Quit();
}
private static void playWav(object sender, EventArgs e) {
//Reference to Thread
thread = new Thread(playWavThread);
thread.Start();
}
private static void playWavThread()
{
var soundFile = @"C:\sound.wav";
using (var wfr = new WaveFileReader(soundFile))
using (WaveChannel32 wc = new WaveChannel32(wfr) { PadWithZeroes = false })
using (var audioOutput = new WaveOut())
{
audioOutput.Init(wc);
audioOutput.Play();
while (audioOutput.PlaybackState != PlaybackState.Stopped)
{
Thread.Sleep(20);
}
audioOutput.Stop();
}
}
}
請給你任何關於這種情況的建議。謝謝
謝謝,工作就像一個魅力。你能解釋爲什麼後臺線程有所作爲嗎? – 2013-05-11 22:33:39
http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx:線程是後臺線程或前臺線程。後臺線程與前臺線程完全相同,只是後臺線程不會阻止進程終止。一旦屬於某個進程的所有前臺線程都終止,公共語言運行庫就結束該進程。任何剩餘的後臺線程都會停止並且無法完成。 – Gjeltema 2013-05-11 22:34:41