Saturday, 15 March 2014

multithreading - C# Thread seems to start multiple times -



multithreading - C# Thread seems to start multiple times -

this programme should rename .txt files .txtok. in test-directory created ~10 textfiles.

at runtime, filenotfoundexception thrown. missing file file renamed in previous thread.

it seems multiple threads have started in 1 loop-iteration!?

static void main(string[] args) { foreach (string s in directory.enumeratefiles(@"c:\test", "*.txt", searchoption.topdirectoryonly)) { new thread(() => { file.move(s, s + "ok"); }).start(); } console.readkey(); }

does had problem simmilar this?

thanks

you experiencing pain of "access modified closure" bug. 1 of mutual problems reported on stackoverflow. search "access modified closure" more details, or read article on subject:

http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/

you can prepare either upgrading c# 5, or doing:

foreach (string s in directory.enumeratefiles(@"c:\test", "*.txt", searchoption.topdirectoryonly)) { string s1 = s; new thread(() => { file.move(s1, s1 + "ok"); }).start(); }

that said, code not code; don't create many threads that. threads heavyweight. treat creating thread you'd treat hiring new employee; wouldn't hire employee rename file , fire them; it's expensive. you'd hire 1 employee rename files.

c# multithreading

No comments:

Post a Comment