Skip to main content
 首页 » 编程设计

c#之在 c# 中线程函数不起作用

2024年02月13日9TianFang

我对这段代码有疑问。该功能正在播放音乐轨道,因此需要一段时间才能完成执行……但是,即使它是线程化的,它也不会在完成之前返回,从而阻碍了程序的其余部分。我可以让函数退出以便程序继续但让音乐保留在它自己的线程上吗?欢迎任何解决方案。

using System; 
using Gtk; 
using NAudio; 
using NAudio.Wave; 
using System.Threading; 
 
public class Trackbox { 
 
    public static void Main() { 
        Application.Init(); 
 
        //Create the Window 
        Window myWin = new Window("Trackbox"); 
        myWin.SetIconFromFile("Assets//logo.png"); 
        myWin.Resize(200, 100); 
 
 
        //Add the label to the form      
        //myWin.Add(myLabel); 
 
        Button playButton = new Button("Play Sound"); 
        //This when playwav is called here, the rest of the application waits for it to finish playing 
 
        playButton.Clicked += new EventHandler(playWav); 
        myWin.Add(playButton); 
 
        myWin.DeleteEvent += delegate { Application.Quit(); }; 
        //Show Everything      
        myWin.ShowAll(); 
 
 
        Application.Run(); 
 
 
    } 
 
    private static void playWav(object sender, EventArgs e) 
    { 
        var soundFile = @"C:\sound.wav"; 
        using (var wfr = new WaveFileReader(soundFile)) 
        using (WaveChannel32 wc = new WaveChannel32(wfr) { PadWithZeroes = false }) 
        using (var audioOutput = new DirectSoundOut()) 
        { 
            audioOutput.Init(wc); 
 
            audioOutput.Play(); 
 
            while (audioOutput.PlaybackState != PlaybackState.Stopped) 
            { 
                Thread.Sleep(20); 
            } 
 
            audioOutput.Stop(); 
        } 
    } 
} 

感谢您的帮助。如果您有任何想法,请发表。

请您参考如下方法:

您的 playWav 与您的 UI 在同一线程上执行。这就是您的 UI 被阻止的原因。

你可以像这样开始一个新线程:

private volatile bool _QuitThread; 
 
private void playWav(object sender, EventArgs e) 
{ 
    _QuitThread = false; 
    Thread thread = new Thread(playWavThread); 
    thread.Start(); 
} 
 
// This method should be called when the music should stop. Perhapse when a button has been pressed. 
private void StopTheMusic()  
{ 
    _QuitThread = true; 
} 
 
private 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 DirectSoundOut()) 
    { 
        audioOutput.Init(wc); 
        audioOutput.Play(); 
        while (!_QuitThread && audioOutput.PlaybackState != PlaybackState.Stopped) 
        { 
            Thread.Sleep(20); 
        } 
        audioOutput.Stop(); 
    } 
} 

编辑

应要求,我添加了退出线程的代码。