Multithreading in c# - Replicate Console class behaviour -
i have application executed 4 function sequentially. inside each function have outputs logged using console.writeline. console internally made redirect data file.
i have change working 4 functions can run in parallel. else being fine concern output logging in file. console.writeline write data in file in random order don't want. want threads finish , log output data in sequence want.
so how capture output inside each thread?
- in string ,
console.writeline4 string make? - capture data in file each thread ,
console.writelinewhen thread finish. - some other class
consoledata read/written in same wayconsoleclass?
i want output same how earlier when application running function sequentially.
if know of output fit in memory, can write output strings , append strings file when done.
there many ways output string. purposes, perhaps easiest create stringwriter each thread. example:
stringwriter output = new stringwriter(); then, replace of console.writeline calls output.writeline.
when thread has finished, can convert output string calling tostring. is:
string threadoutput = output.tostring(); then take each thread's output , write file in order want.
if output large fit in memory, have each thread open streamwriter, write file. when 4 threads done, can open each of files in turn, read data, , write output. like:
using (filestream outputfile = file.openwrite(outputfilename)) { // following each thread's output using (filestream threadfile = file.openread(inputfilename)) { threadfile.copyto(outputfile); } }
Comments
Post a Comment