c# - using a Lock on a log Writer to Prevent Errors -


I am downloading images from the web using a foreach and functions, and saving them to the local level. After doing this, I am saying the file name on the log name and then downloading. The problem is that I can try to write two work logs due to an error at the same time. I want to be able to lock the logs if any other work is writing on this, but I'm not sure how? So far I have:

  int files download = 0; Foreach (var filename in ListOfFileNames) {Tasks. Factor Lock startup ((=) = {// download file} {log} Virus line (string format ("downloaded file: {0}", f.FullName), log status.Success );} downloads ++;}  

do I need to lock the files downloaded variable, or it is a simple operation ++ Do not matter?

Edit

Static log class:

  Public Anonymous status {Info, Error, Success} Private Stable String Directory {get; set;} Public Static Zero CheckandCreateLogDirectory (string directoryPath) {if (!! System.IO.Directory.Exists (DirectoryPath)) {System.IO.Directory.CreateDirectory (DirectoryPath);} Directory = DirectoryPath;} Public Static Zero WriteLine (String Listline, Position Position) {If (directory == empty) {Using CheckandCreateLogDirectory (". \\ log \\");} (Sy Stem.IO.StreamWriter objWriter = New system.io.stream Vector (Directory + "Log" + DateTime.Now.ToString ("ddMMyyyy") + ".log", true)) {objWriter.WriteLine (string.Format ("[{0}] {1} \ t {2} ", DateTime.Now, status.ToString (), Write-line)); There are two things that come to mind:  

/ P>

1) Move your locking to the written line () method - Every time you want to log some, there is no point to repeat the code

  Private static object _lockMe = new object (); Public static zero WriteLine (string listline, status status) {lock (_lockMe) {if (directory == empty) {CheckandCreateLogDirectory (". \\ log \\"); } ("DdMMyyyy") + ".log",) {objWriter.WriteLine (string.Format (" [{0}] {1} \ t {2} ", date time.Now, position. Toastring (write, line)); }}  

2) You are downloading a file in a worker thread, but updating the log after the worker is queued once - this file will be downloaded before . As a result, I move logging into the worker thread, as follows:

  int filesDownloaded = 0; Foreach (var filename in ListOfFileNames) {Tasks. Factory Start (path) = & gt; {DownloadMile file (path); Logs. Virusline (string format ("downloaded file: {0}", path), log. Status success); Lock (this link) {Downloads files ++;}}, filename); }  

Comments

Popular posts from this blog

sqlite3 - UPDATE a table from the SELECT of another one -

c# - Showing a SelectedItem's Property -

javascript - Render HTML after each iteration in loop -