c# - Could a System.Diagnostics.Process instance be garbage collected? -
i'm using system.diagnostics.process class convert wav file mp3 file in separated process. method job this:
public void convertwavtomp3 (tempfile srcfile, string title, action<tempfile, exception> complete) { var argument_fmt = "-s --resample 16 --tt {0} --add-id3v2 {1} {2}"; var dstfile = new tempfile(path.gettempfilename()); var proc = new system.diagnostics.process (); proc.enableraisingevents = true; proc.startinfo.useshellexecute = false; proc.startinfo.filename = "lame"; proc.startinfo.arguments = string.format (argument_fmt, title, srcfile.path, dstfile.path); proc.exited += delegate(object sender, eventargs e) { proc.waitforexit(); srcfile.delete(); complete(dstfile, null); }; proc.start(); }
i'm worried gc because proc local variable, theoretically doesn't exist anymore when method returns. therefor, proc can garbage collected , callback function complete never called.
but don't want record proc somewhere , dispose after process exits, expose internal mechanism of how wav mp3 conversion implemented.
is concern gc valid? if gc of potential problem, there way prevent without having return proc in method?
btw, i'm using mono on linux.
edit
thanks replies. i'm confirmed need keep copy of process. here's did:
public class lameconverter : iaudioconverter { // need store reference process in case gced. ilist<process> _proclist = new list<process>(); public void convertwavtomp3 (tempfile srcfile, string title, action<tempfile, exception> complete) { // .. skipped .. proc.exited += delegate(object sender, eventargs e) { lock (this) { _proclist.remove(proc); } proc.dispose(); srcfile.delete(); complete(dstfile, null); }; proc.start(); lock (this) { _proclist.add(proc); } } }
as long caller holds reference lameconverter, don't need worry gc anymore.
any object without root in application candidate garbage collection. in order ensure callback fires need find place store reference proc
otherwise have undefined behavior.
one option in case return object encapsulates proc
without exposing via public interface. unfortunately in case must leak bit of underlying implementation caller of convertwavtomp3
in order ensure desired behavior occurs.
Comments
Post a Comment