c# - Will using System.IO.StreamWriter & WriteLineAsync wait for a file that is being accessed by another thread -
i have following code inside asp.net mvc-5 web application :-
system.io.streamwriter file = new system.io.streamwriter(server.mappath("~/logs/logs.txt"), true); await file.writelineasync("execution started @ " + system.datetime.now.tostring()); file.close();
now question happen if 2 methods execute above code @ same time? 1 of them fail ? since trying write txt file being accessed thread ?
you can leverage tpl dataflow nicely such queue , mechanism writes file never occur in parallel (by using maxdegreeofparallelism
)
public class logger { private actionblock<string> block; public logger(string filepath) { block = new actionblock<string>(async message => { using(var f = file.open(filepath, filemode.openorcreate, fileaccess.write)) { f.position = f.length; using(var sw = new streamwriter(f)) { await sw.writelineasync(message); } } }, new executiondataflowblockoptions{maxdegreeofparallelism = 1}); } public void log(string message) { block.post(message); } }
Comments
Post a Comment