我正在编写一个小型I/O库来协助更大的(业余爱好)项目.该库的一部分对文件执行各种功能,该文件通过FileStream对象读/写.每次StreamReader.Read(...)通过时,
我将启动一个事件,该事件将在主应用程序中用于显示进度信息.在循环中进行的处理是有缺陷的,但不是太耗时(例如,它可能只是一个简单的文件副本,或者可能涉及加密...).
我的主要问题是:使用的最佳内存缓冲区大小是多少?考虑到物理磁盘布局,我可以选择2k,这将覆盖CD扇区大小,并且是512字节硬盘扇区的很好的倍数.在抽象树的上方,你可以选择一个更大的缓冲区,它可以一次读取整个FAT簇.我意识到今天的PC,我可以选择更多的内存饥饿选项(例如几个MiB),但随后我增加了UI更新之间的时间,并且用户感觉到响应速度较慢的应用程序.
顺便说一句,我最终希望为FTP/HTTP服务器上托管的文件提供类似的界面(通过本地网络/快速DSL).那些最佳的内存缓冲区大小(再次,感知响应性与性能之间的"最佳情况"权衡)?
我一直在尝试解决这个"并发编程"考试练习(在C#中):
知道
Stream该类包含int Read(byte[] buffer, int offset, int size)和void Write(byte[] buffer, int offset, int size)方法,在C#中实现NetToFile将从NetworkStream net实例接收的所有数据复制到FileStream file实例的方法.要进行传输,请使用异步读取和同步写入,以避免在读取操作期间阻塞一个线程.当net读取操作返回值0 时,传输结束.为简化起见,不必支持操作的受控取消.
void NetToFile(NetworkStream net, FileStream file);
Run Code Online (Sandbox Code Playgroud)
我一直试图解决这个问题,但我正在努力解决与问题本身相关的问题.但首先,这是我的代码:
public static void NetToFile(NetworkStream net, FileStream file) {
byte[] buffer = new byte[4096]; // buffer with 4 kB dimension
int offset = 0; // read/write offset
int nBytesRead = 0; // number of bytes read on each cycle
IAsyncResult ar;
do {
// …Run Code Online (Sandbox Code Playgroud) 我经常看到4096用作整个地方的默认缓冲区大小.是否有任何理由选择4096而不是另一个值?
我在web api控制器中使用以下异步代码来处理XML文件.一切都按预期工作,但这是正确使用async/await方法.我基本上从XML文件中提取所有图像,然后将它们保存到磁盘.我想尝试最小化文件io的影响.
public async Task<HttpResponseMessage> PostFile()
{
await Task.WhenAll(this.ProcessProofOfPressenceImages(address, images, surveyReference), this.ProcessSketchImages(propertyPlans, images, surveyReference), this.ProcessExteriorImages(exteriorSketch, images, surveyReference));
//db code
}
private async Task ProcessProofOfPressenceImages(Dictionary<object, object> container, List<Dictionary<string, string>> images, string surveyReference)
{
if(images != null)
{
await Task.WhenAll(this.ProcessImagesHelper(container, images, surveyReference, "propertyImage"));
}
}
private async Task ProcessSketchImages(Dictionary<object, object> container, List<Dictionary<string, string>> images, string surveyReference)
{
if(images != null)
{
await Task.WhenAll(this.ProcessImagesHelper(container, images, surveyReference, "sketchPlanImage"), this.ProcessImagesHelper(container, images, surveyReference, "sketchFrontImage"), this.ProcessImagesHelper(container, images, surveyReference, "sketchRearImage"), this.ProcessImagesHelper(container, images, surveyReference, "sketchLeftSideImage"), this.ProcessImagesHelper(container, images, surveyReference, "sketchRightSideImage")); …Run Code Online (Sandbox Code Playgroud) c# ×4
.net ×2
buffer ×2
streamwriter ×2
asp.net-4.5 ×1
asynchronous ×1
concurrency ×1
file ×1
filestream ×1
optimization ×1
size ×1