在C#中调用线程并记录到文本文件的更好方法 [英] better way of invoking thread and logging to text file in C#

查看:214
本文介绍了在C#中调用线程并记录到文本文件的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将日志记录写为文本文件的程序.

I have a program which write logging as Text File.

namespace logging
{
    using System;
    using System.IO;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.Text;

    public class log
    {
        private static string lpath;

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        public static void Info(string user, string info, string txt)
        {
            StreamWriter writer;
            string str = Assembly.GetExecutingAssembly().GetName().CodeBase.ToString();

            .....

            if (!File.Exists(path))
            {
                writer = new StreamWriter(path, true);
                writer.WriteLine(str3 + " " + info + " => " + txt);
                writer.Flush();
                writer.Close();
            }
            else
            {
                writer = File.AppendText(path);
                writer.Write(str3 + " " + info + " => " + txt + "\n");
                writer.Flush();
                writer.Close();
            }
        }
    }
}

然后我有一个功能.

private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    Thread thread_BP_Print = new Thread(BoardingPass_Print);          
    thread_BP_Print.Start();

    // Simultaneously, do something on the main thread.
    BaggageTag_Print();
    bgw.RunWorkerAsync();
}

两个内部函数(BoardingPass_Print()BaggageTag_Print())调用相同的日志记录函数.

Two of the inner functions (BoardingPass_Print() and BaggageTag_Print()) call the same logging function.

logging.log.Info(username, "Query Trace > ", sql);

由于我调用线程方法,我认为我遇到了错误:

Because of my invoking thread methods, I think I face the error:

该进程无法访问文件'C:\ Folder \ 2012-01-17-Name.txt',因为该文件正在被另一个进程使用.

The process cannot access the file 'C:\Folder\2012-01-17-Name.txt' because it is being used by another process.

有人能给我更好的解决方案来与线程交互并记录到文本文件而不会遇到这样的错误消息吗?

Could anyone give me better solution to interact with thread and logging to text file without facing error message like this?

每个建议都会很感激.

推荐答案

您必须使编写线程安全(使用lock).您当前的代码也不是异常安全的. 您可以使用正确的库方法来解决这两个问题.

You would have to make the writing thread-safe (with lock). Your current code also is not exception-safe. You can solve both issues by using the right library method.

您不能(轻松地)确保从多个进程安全访问文件,但是只要文件仅由应用程序的1个实例编写,就可以同步线程.

You cannot (easily) assure safe access to a file from multiple processes, but as long as its only written by 1 instance of the application you can sync the threads.

private static object locker = new object();
public static void Info(string user, string info, string txt)
{        
    string str = Assembly.GetExecutingAssembly().GetName().CodeBase.ToString();
    string str3 = ...
    lock (locker)
    {
       File.AppendAllText(path, str3 + " " + info + " => " + txt + "\n");
    }
}

AppendAllText是静态方法,它将正确处理新文件/现有文件的问题以及资源管理.

AppendAllText is a static method, it will handle the new/existing file issue and the resource management correctly.

这篇关于在C#中调用线程并记录到文本文件的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆