如何用多个线程在单个文件中写入? [英] How to write in a single file with multiple threads?

查看:25
本文介绍了如何用多个线程在单个文件中写入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C# 创建 Windows 应用程序,我想在其中使用多个线程写入多个文件.我从不同的端口获取数据,并且每个端口都有一个关联的文件.是否可以为每个端口创建线程并一次又一次地使用相同的线程将数据写入相应的文件?假设我从端口 10000,10001,10002 获取数据,并且有 10000.txt、10001.txt 和 10002.txt 三个文件.我必须创建三个线程来分别将数据写入这三个文件,并且我想一次又一次地使用这些线程.是否可以?如果可能,请您提供一小部分代码示例吗?

I am creating Windows Application in C# in which I want to write in multiple files with multiple threads. I am getting data from different ports and there is one file associated with every port. Is it possible that creation of thread for every port and use the same thread again and again for writing data to respective file? Suppose I am getting data from ports 10000,10001,10002 and there are three files as 10000.txt, 10001.txt and 10002.txt. I have to create three threads for writing data to these three files respectively and I want to use these threads again and again. Is it possible? Please can you give a small sample of code if possible?

推荐答案

正如评论中提到的,这是自找麻烦.

As mentioned in the comments, this is asking for trouble.

所以,你需要一个线程安全的编写器类:

So, you need to have a thread-safe writer class:

public class FileWriter
{
    private ReaderWriterLockSlim lock_ = new ReaderWriterLockSlim();
    public void WriteData(/*....whatever */)
    {
        lock_.EnterWriteLock();
        try
        {
            // write your data here
        }
        finally
        {
            lock_.ExitWriteLock();
        }
    }

} // eo class FileWriter

这适合被多个线程调用.但是,有一个警告.很可能存在锁争用.我使用了一个 ReadWriterLockSlim 类,因为您可能也想使用读锁,而且该类还允许您从读取状态升级.

This is suitable for being called by many threads. BUT, there's a caveat. There may well be lock contention. I used a ReadWriterLockSlim class, because you may want to do read locks as well and hell, that class allows you to upgrade from a read state also.

这篇关于如何用多个线程在单个文件中写入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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