c# - Waiting for ThreadPool to finish -


i developed application saves 10000 lines of lorem ipsum in .txt file on disk. used streamwriter write these lines, , threadpool distribute computational process available threads/cores.

the saving fast, 1 million lines, problem is, not lines saved , last 1 saved partially. when close program, writes file again reason.

i have following string:

string loremipsum = "lorem ipsum dolor sit amet, consectetur adipiscing elit, sed eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; 

and rest of code is:

    private streamwriter writer = new streamwriter("loremipsum.txt");     private object lockobject = new object();      // button initiates process     private void btnsave_click(object sender, routedeventargs e)     {         (int = 1; <= 10000; i++)         {             threadpool.queueuserworkitem(state =>             {                 savefile(writer, loremipsum);             });         }     }      private void savefile(streamwriter w, string text)     {         lock (lockobject)         {             w.writeline(text);         }     } 

since streamwriter not thread-safe, i'm using locking object.

if open .txt file program running has 9998 lines last 1 being incomplete.

enter image description here

if close program, rewrites file again, adding lines, again last 1 incomplete. why this?

i suppose lines saved partially because threadpool's threads need time finish work. correct? if so, how can achieve that?

threadpool making background threads perform tasks stop aborted if main thread aborted. have wait threads finish , flush stream. missing last lines, more have flush() issue there,not aborted threads.

i trust know code worse doing work in single thread. there no real parallelism happening there while overhead created.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -