c# - Memory leak in MediaPlayer -
can please explain why following program runs out of memory?
class program { private static void threadroutine() { system.windows.media.mediaplayer player = new system.windows.media.mediaplayer(); } static void main(string[] args) { thread athread; int iteration = 1; while (true) { athread = new thread(threadroutine); athread.start(); athread.join(); console.writeline("iteration: " + iteration++); } } }
to fair, specific exception system.componentmodel.win32exception
, "not enough storage available process command." exception happens on attempt create new mediaplayer.
mediaplayer not implement idisposable
interface i'm not sure if there other cleanup necessary. didn't find in mediaplayer documentation.
my guess thread objects created aren't garbage collected in time.
as stating in comment are out of luck respect finding solution doesn't involve memory leak, i'm posting alternative answer though doesn't attempt answer original question.
if use threadpool instead, (a) runs faster , (b) not crash.
class program { private static void threadroutine(object state) { var player = new mediaplayer(); var iteration = (int)state; if (iteration % 1000 == 0) { console.writeline("executed: " + state); } } static void main(string[] args) { (int = 0; < 10000000; i++) { if (i % 1000 == 0) { console.writeline("queued: " + i); } threadpool.queueuserworkitem(threadroutine, i); } } }
on machine, have no problem creating 10 million thread-pool threads in few seconds.
queued: 9988000 queued: 9989000 queued: 9990000 queued: 9991000 executed: 9989000 executed: 9990000 executed: 9991000 executed: 9988000 queued: 9992000 executed: 9992000 queued: 9993000 queued: 9994000 queued: 9995000 executed: 9994000 executed: 9993000 queued: 9996000 executed: 9996000 executed: 9995000 queued: 9997000 executed: 9997000 queued: 9998000 executed: 9998000 queued: 9999000 executed: 9999000 press key continue . . .
Comments
Post a Comment