Filewrite很多时候,多台机器执行此命令,问题 [英] Filewrite, many times, multiple machines doing this command, Problem

查看:83
本文介绍了Filewrite很多时候,多台机器执行此命令,问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个Web服务,该服务可以一次(异步)接受多个连接.在此Web服务中,我尝试将一行文本写入日志文件,这有时会起作用.但是,经过一定数量的写入后,它会中断(编辑者的注:OP需要澄清中断和中断的方式).

以下代码是我用来写入日志文件的代码.我尝试添加/删除fs.Close()和fs.Flush(),但仍然收到相同的错误(编辑提示:OP应包含错误消息).

请记住,我是一名CS学生,是一名实习生,所以我有点没有经验(编者注:要温柔).有人告诉我,如果我需要任何帮助,可以使用此网站.提前谢谢!

I am running a web service that can accept multiple connections at once (asynchronously). In this web service, I am attempting to write a line of text to a log file, which works some of the time. However, after a certain number of writes, it breaks (editor''s note: OP needs to clarify what breaks and how).

The below code is what I am using to write to the log file. I have tried adding/removing fs.Close() and fs.Flush(), but I still get the same error (editor''s note: OP should include the error message).

Please keep in mind that I am a CS student who is an intern, so I am a little inexperienced (editor''s note: be gentle). I was told I could use this site if I needed help with anything. Thanks in advance!

using (FileStream fs = new FileStream(string.Format(@"{0}\Information logs\{1}",
    Properties.Settings.Default.InformationLogsDestination, logName),
    FileMode.Append, FileAccess.Write))
{
    StreamWriter w = new StreamWriter(fs, Encoding.UTF8);
    w.WriteLine(DateTime.Now.ToString("G") + " posting to '" +
        message + "' to list " + name + " in Database.");
    w.Flush();
    w.Close();
    fs.Close();
}

推荐答案

或者,写入数据库或事件日志而不是文件.
Alternatively, write to a database or the event log rather than a file.


lock(myStaticVariable)
{
    // Code to write to file.
}



使用静态变量锁定并确保没有两个线程一次写入同一文件.



Use a static variable to lock on and ensure no two threads are writing to the same file at once.


每个程序都应使用自己的文件...或Web服务应执行所有操作日志记录.

如果经常使用同一文件,最好避免使用它们.

给定以上代码,如果一个程序打开文件,而第二个程序尝试在第一个程序完成之前打开文件,则将引发异常,因为文件被第一个程序锁定.

因此,如果您仍然认为使用单个文件将是捕获适当的异常并稍后重试该操作,则这是一个简单的解决方案.

顺便说一下,这样的程序无法很好地扩展.因此,该解决方案仅适用于一些不大量使用日志的应用程序.
Each program should uses its own file... or the web service should do all the logging.

It is preferable to avoid using the same file remotly particulary if they are used a lot.

Given the above code, if one program open the file and a second one try to open it before the first program has finished, then an exception will be raised since the file is lock by the first program.

Thus a simple solution if you still think that using a single file would be to catch the appropriate exception and retry the operation a bit later.

By the way such program won''t scale well. Thus that solution could be adequat only for a few applications that do not uses the log intensively.


这篇关于Filewrite很多时候,多台机器执行此命令,问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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