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

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

问题描述

我正在C#中创建Windows应用程序,我想在多个文件中写入多个线程。我从不同的端口获取数据,并且每个端口都有一个文件关联。是否有可能为每个线程创建线程端口并一次又一次地使用相同的线程写入数据到相应的文件?
假设我从端口10000,10001,10002获取数据,并有三个文件,分别为10000.txt,10001.txt和10002.txt。我必须创建三个线程分别写入这三个文件的数据,我想一次又一次地使用这些线程。是否有可能吗?如果可能,请给出一小段代码示例?
<解决方案

正如在评论中提到的,这是要求麻烦。

所以,你需要有一个线程安全的作家类:

  public class FileWriter 
{
private ReaderWriterLockSlim lock_ = new ReaderWriterLockSlim ;
public void WriteData(/ * .... whatever * /)
{
lock_.EnterWriteLock();
try
{
//在这里写入你的数据
}
finally
{
lock_.ExitWriteLock();


$ b $ // eo class FileWriter



这适合被许多线程调用。但是,有一个警告。有可能是锁争夺。我使用了一个 ReadWriterLockSlim 类,因为你可能想要读取锁以及地狱,这个类也允许你从读状态升级。


i am creating windows application in C# in which i want to write in a multiple file 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

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天全站免登陆