重新启动运行线程

时间:2013-05-11 22:05:31

标签: c# multithreading gtk#

我是线程新手,需要很多帮助。 我有基于启动线程的事件的代码。问题是我松散了对线程和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();
    }

}
}

请提供有关此情况的任何建议。感谢

2 个答案:

答案 0 :(得分:0)

好吧,没有深入到线程以及如何使用线程和诸如此类的东西(我建议在C#中更多地阅读线程然后再次尝试 - 通过C#的书籍CLR在线程上有很多,当然还有很多站点在互联网上),为了让您的应用程序在这种情况下死亡,您应该将您的线程设置为后台线程:

private static void playWav(object sender, EventArgs e) {
    //Reference to Thread
    thread = new Thread(playWavThread);
    thread.IsBackground = true;
    thread.Start();
}

非后台线程使您的应用程序无法终止,但后台线程在进程关闭时会很快死亡。对于对正在运行的应用程序不重要的任何线程,您应该将其设置为后台线程。

答案 1 :(得分:0)

此外,根据最终目标,您可能会考虑使用BackgroundWorker。它似乎提供了您需要的功能,能够实现线程的取消。此外,以这种方式执行此操作的好处是,使用BackgroundWorker会更快,因为它们使用来自线程池的线程。缺点是可用的数量有限,所以如果你使用了很多,他们可以互相争夺可用的线程池线程。

相关问题