c# - Playing .wav files in queue -
trying play .wav files in thread safe queue. calls may triggered @ random thread must play in sequence. problem when phone call play(string[] files) 3 file names (currently testing ui thread), lastly file played 3 times, , 2 first never played. can't see causes this..?
would appreciate suggestion easier way this, know why doesn't work.
public class sound { static actionqueue actionqueue; public static string mediafolder { get; set; } private static object syncroot = new object(); static audio() { actionqueue = new actionqueue(); } /// <summary> /// plays .wav in async queue. /// </summary> /// <param name="filename"></param> public static void play(string filename) { actionqueue.add(() => playsound(filename)); } public static void play(string[] files) { console.writeline("id0: " + thread.currentthread.managedthreadid); foreach (string f in files.tolist()) { console.writeline("queue file: " + f); actionqueue.add(() => playsound(f)); } } private static void playsound(string f) { console.writeline("id1: " + thread.currentthread.managedthreadid); var filename = f; console.writeline("play queue: " + filename); filename = path.combine(mediafolder, filename); if (!path.hasextension(filename)) filename = filename + ".wav"; if (!file.exists(filename)) return; string ext = path.getextension(filename); if (ext != ".wav") return; console.writeline("playing: " + filename); soundplayer player = new soundplayer(filename); player.playsync(); } } public class actionqueue { private blockingcollection<action> persisterqueue = new blockingcollection<action>(); public actionqueue( ) { var thread = new thread(processworkqueue); thread.isbackground = true; thread.start(); } private void processworkqueue() { while (true) { var nextwork = persisterqueue.take(); nextwork(); } } public void add(action action) { persisterqueue.add(action ); } }
it's classic captured-loop-variable-in-a-closure problem.
you need take re-create of loop variables i.e.
foreach (string f in files.tolist()) { var re-create = f; console.writeline("queue file: " + f); actionqueue.add(() => playsound(copy)); } the reason beingness delegates beingness passed actionqueue not executed until loop has finished. time, of course, variable f has changed value.
c# .net multithreading queue wav
No comments:
Post a Comment