如何尽可能有效地处理大量并发磁盘的写入请求 [英] How to handle large numbers of concurrent disk write requests as efficiently as possible

查看:902
本文介绍了如何尽可能有效地处理大量并发磁盘的写入请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设下面的方法被调用不同线程数千倍在.NET 4的应用程序。什么是处理这种情况的最好方法?记者了解到,该盘是这里的瓶颈,但我想在WriteFile的()方法来快速返回。



数据可以是可高达几MB。我们谈论线程池,TPL或类似的?

 公共无效WriteFile的(字符串文件名,MemoryStream的数据)
{

{
按(的FileStream磁盘文件= File.OpenWrite(文件名))
{
Data.WriteTo(磁盘文件);
DiskFile.Flush();
DiskFile.Close();
}
}
赶上(例外五)
{
Console.WriteLine(e.Message);
}
}


解决方案

由于你说的那个文件不需要被写入为了,也不立即,最简单的方法是使用工作

 私人无效WriteFileSynchronous(字符串文件名,MemoryStream的数据)
{
Task.Factory.StartNew(()=> WriteFileSynchronously(文件名,数据) );
}

私人无效WriteFileSynchronous(字符串文件名,MemoryStream的数据)
{

{$ B $使用B(的FileStream磁盘文件= File.OpenWrite (文件名))
{
Data.WriteTo(磁盘文件);
DiskFile.Flush();
DiskFile.Close();
}
}

赶上(例外五)
{
Console.WriteLine(e.Message);
}
}



TPL使用线程池内部,并应相当有效,甚至对于大量的任务。


Say the method below is being called several thousand times by different threads in a .net 4 application. What’s the best way to handle this situation? Understand that the disk is the bottleneck here but I’d like the WriteFile() method to return quickly.

Data can be can be up to a few MB. Are we talking threadpool, TPL or the like?

public void WriteFile(string FileName, MemoryStream Data)
{
   try
   {
      using (FileStream DiskFile = File.OpenWrite(FileName))
      {
         Data.WriteTo(DiskFile);
         DiskFile.Flush();
         DiskFile.Close();
      }
   }
   catch (Exception e)
   {
      Console.WriteLine(e.Message);
   }
}

解决方案

Since you say that the files don't need to be written in order nor immediately, the simplest approach would be to use a Task:

private void WriteFileSynchronous(string FileName, MemoryStream Data)
{
    Task.Factory.StartNew(() => WriteFileSynchronously(FileName, Data));
}

private void WriteFileSynchronous(string FileName, MemoryStream Data)
{
    try
    {
        using (FileStream DiskFile = File.OpenWrite(FileName))
        {
            Data.WriteTo(DiskFile);
            DiskFile.Flush();
            DiskFile.Close();
        }
    }

    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
}

The TPL uses the thread pool internally, and should be fairly efficient even for large numbers of tasks.

这篇关于如何尽可能有效地处理大量并发磁盘的写入请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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