线程安全的StreamWriter C#怎么办呢? 2 [英] Thread safe StreamWriter C# how to do it? 2

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

问题描述

所以这是我的最后一个问题的延续 - 这样的问题是
什么​​是建立一个程序,它是线程安全而言,它需要两倍的值写入文件的最好方法。如果。

功能,节省了通过StreamWriter的价值观正在被多个线程?请告诉我这样做的最好办法叫什么名字?

和我修改在MSDN中发现一些代码,怎么样的以下?这一次正确的一切写入文件。

 命名空间SafeThread 
{
类节目
{
静态无效的主要()
{
线程丝=新的线程();

的AutoResetEvent autoEvent =新的AutoResetEvent(假);

螺纹regularThread =
新主题(新的ThreadStart(threader.ThreadMethod));
regularThread.Start();

ThreadPool.QueueUserWorkItem(新WaitCallback(threader.WorkMethod),
autoEvent);

//等待前台线程结束。
regularThread.Join();

//等待后台线程结束。
autoEvent.WaitOne();
}
}


级线程
{
名单,LT;双>值=新的List<双>();
静态只读对象更衣室=新的对象();
StreamWriter的作家=新的StreamWriter(文件);
静态INT bulkCount = 0;
静态INT bulkSize = 100000;

公共无效ThreadMethod()
{
锁(柜)
{
,而(bulkCount< bulkSize)
Values.Add( bulkCount ++);
}
bulkCount = 0;
}

公共无效WorkMethod(对象将stateInfo)
{
锁(柜)
{
的foreach(中值双V)
{
writer.WriteLine(V);
writer.Flush();
}
}
//信号,这个线程完成。
((的AutoResetEvent)将stateInfo)。设置();
}
}
}


解决方案

QueueUserWorkItem 费用最低的API螺纹的。我不会使用它们,除非我绝对,最后,没有其他选择。尝试工作类一个更高层次的抽象。有关详细信息,请看看我最近的博客帖子关于这个问题



您也可以使用 BlockingCollection<双> 正确的生产者/消费者队列,而不是试图由专人用的最低可同步API打造有一个



正确重塑这些车轮是相当困难。我强烈建议使用专为此类需求的类(工作 BlockingCollection ,具体)。它们是内置于.NET 4.0框架和可作为一个附加的.NET 3.5


So this is a continuation from my last question - So the question was "What is the best way to build a program that is thread safe in terms that it needs to write double values to a file. If the function that saves the values via streamwriter is being called by multiple threads? Whats the best way of doing it?"

And I modified some code found at MSDN, how about the following? This one correctly writes everything to the file.

namespace SafeThread
{
    class Program
    {
        static void Main()
        {
            Threading threader = new Threading();

            AutoResetEvent autoEvent = new AutoResetEvent(false);

            Thread regularThread =
                new Thread(new ThreadStart(threader.ThreadMethod));
            regularThread.Start();

            ThreadPool.QueueUserWorkItem(new WaitCallback(threader.WorkMethod),
                autoEvent);

            // Wait for foreground thread to end.
            regularThread.Join();

            // Wait for background thread to end.
            autoEvent.WaitOne();
        }
    }


    class Threading
    {
        List<double> Values = new List<double>();
        static readonly Object locker = new Object();
        StreamWriter writer = new StreamWriter("file");
        static int bulkCount = 0;
        static int bulkSize = 100000;

        public void ThreadMethod()
        {
            lock (locker)
            {
                while (bulkCount < bulkSize)
                    Values.Add(bulkCount++);
            }
            bulkCount = 0;
        }

        public void WorkMethod(object stateInfo)
        {
            lock (locker)
            {
                foreach (double V in Values)
                {
                    writer.WriteLine(V);
                    writer.Flush();
                }
            }
            // Signal that this thread is finished.
            ((AutoResetEvent)stateInfo).Set();
        }
    }
}

解决方案

Thread and QueueUserWorkItem are the lowest available APIs for threading. I wouldn't use them unless I absolutely, finally, had no other choice. Try the Task class for a much higher-level abstraction. For details, see my recent blog post on the subject.

You can also use BlockingCollection<double> as a proper producer/consumer queue instead of trying to build one by hand with the lowest available APIs for synchronization.

Reinventing these wheels correctly is surprisingly difficult. I highly recommend using the classes designed for this type of need (Task and BlockingCollection, to be specific). They are built-in to the .NET 4.0 framework and are available as an add-on for .NET 3.5.

这篇关于线程安全的StreamWriter C#怎么办呢? 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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