Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 7th, 2012  |  syntax: None  |  size: 1.82 KB  |  hits: 20  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. better way of invoking thread and logging to text file in C#
  2. namespace logging
  3. {
  4.     using System;
  5.     using System.IO;
  6.     using System.Reflection;
  7.     using System.Runtime.InteropServices;
  8.     using System.Text;
  9.  
  10.     public class log
  11.     {
  12.         private static string lpath;
  13.  
  14.         [DllImport("kernel32")]
  15.         private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
  16.         public static void Info(string user, string info, string txt)
  17.         {
  18.             StreamWriter writer;
  19.             string str = Assembly.GetExecutingAssembly().GetName().CodeBase.ToString();
  20.  
  21.             .....
  22.  
  23.             if (!File.Exists(path))
  24.             {
  25.                 writer = new StreamWriter(path, true);
  26.                 writer.WriteLine(str3 + " " + info + " => " + txt);
  27.                 writer.Flush();
  28.                 writer.Close();
  29.             }
  30.             else
  31.             {
  32.                 writer = File.AppendText(path);
  33.                 writer.Write(str3 + " " + info + " => " + txt + "n");
  34.                 writer.Flush();
  35.                 writer.Close();
  36.             }
  37.         }
  38.     }
  39. }
  40.        
  41. private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  42. {
  43.     Thread thread_BP_Print = new Thread(BoardingPass_Print);          
  44.     thread_BP_Print.Start();
  45.  
  46.     // Simultaneously, do something on the main thread.
  47.     BaggageTag_Print();
  48.     bgw.RunWorkerAsync();
  49. }
  50.        
  51. logging.log.Info(username, "Query Trace > ", sql);
  52.        
  53. private static object locker = new object();
  54. public static void Info(string user, string info, string txt)
  55. {        
  56.     string str = Assembly.GetExecutingAssembly().GetName().CodeBase.ToString();
  57.     string str3 = ...
  58.     lock (locker)
  59.     {
  60.        File.AppendAllText(path, str3 + " " + info + " => " + txt + "n");
  61.     }
  62. }