C#写安全文本文件线程堆 [英] C# Writing To Text File Safely With Heaps of Threads

查看:171
本文介绍了C#写安全文本文件线程堆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,所以我的程序有大约30个线程,而我需要一个日志一些通过每个线程收集的信息。



我做的方式,这是按:创建的类节目中的公共静态StringBuilder的,然后每个线程调用AppendLine方法来此StringBuilder的实例,每隔几分钟。然后,每隔30分钟另一个线程专用于使用StreamWriter的正是这么做的。



例如写:

 公共类节目
{
公共静态StringBuilder的SB =新的StringBuilder();
公共静态无效的主要(字串[] args)
{
//开始的所有线程
}
}

公共类实例
{
线T1 =新的Thread(()=>
{
,而(真)
{
DoSomething的();
}
});

螺纹logThread =新的Thread(()=>而(真)
{
使用(StreamWriter的作家=新的StreamWriter
{
(路径))
{
writer.Write(Program.sb);
}
}
});

公共静态无效DoSomething的()
{
//会做一些了几分钟。
Program.sb.AppendLine(一些文本之前聚集......不同每次!);
}
}

这是这样做的好方法吗?



感谢

解决方案

没有,在的StringBuilder <> / code>不使用它的同时线程安全的,所以多线程可能会损坏它。



同步接入到 StringBuilder的使用锁定关键字。让它私有,并提供公有方法与它安全地工作:

 私有静态StringBuilder的_sb =新的StringBuilder(); 
私有静态对象_sbSync =新的对象();

公共静态无效AppendLine(串线){
锁(_sbSync){
_sb.appendLine(线);
}
}

公共静态字符串GetLines(){
锁(_sbSync){
字符串结果= _sb.ToString();
_sb =新的StringBuilder();
返回结果;
}
}


Okay so my program has around 30 threads, and I need to make a log of some of the information gathered through each threads.

The way I did this is by: Creating a public static StringBuilder in the class Program, and then each thread will call the AppendLine method to this StringBuilder instance every few minutes. Then, every 30 minutes another Thread dedicated to writing using a StreamWriter does exactly that.

For example:

public class Program
{
    public static StringBuilder sb  = new StringBuilder();
    public static void Main(string[] args)
    {
        // Start all threads
    }
}

public class Example
{
    Thread t1 = new Thread(() =>
    {
        while(true)
        {
            DoSomething();
        }
    });

    Thread logThread = new Thread(() =>
    {
        while(true)
        {
            using(StreamWriter writer = new StreamWriter(Path))
            {
                writer.Write(Program.sb);
            }
        }
    });

    public static void DoSomething()
    {
        // Will do something for a few minutes.
        Program.sb.AppendLine("Some text gathered before...different everytime!");
    }
}

Is this a okay way of doing this?

Thanks

解决方案

No, the StringBuilder is not thread safe, so multiple threads using it at the same time may corrupt it.

Synchronise the access to the StringBuilder using the lock keyword. Make it private, and supply public methods to work with it safely:

private static StringBuilder _sb = new StringBuilder();
private static object _sbSync = new Object();

public static void AppendLine(string line) {
  lock (_sbSync) {
    _sb.appendLine(line);
  }
}

public static string GetLines() {
  lock (_sbSync) {
    string result = _sb.ToString();
    _sb = new StringBuilder();
    return result;
  }
}

这篇关于C#写安全文本文件线程堆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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