异常后文件保持打开状态 [英] File remains open after exception

查看:81
本文介绍了异常后文件保持打开状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我需要一些最佳做法方面的支持.

我从事一项服务,每分钟在服务器上运行.假设我打开一个文件来注册一些操作,即一个日志文件.我遇到异常,我需要以某种方式关闭文件,而不必在Try Catch块中插入所有代码...
计时器下一次执行时,它将尝试再次访问该文件并被打开,因此无法添加信息.

你会怎么做?

请帮帮我.

在此先谢谢您.

Hi Everybody,

I need some support in best practices.

I work on a service, running each minute on a server. Suppose I open a file to register some actions, a log file. I get an exception, and I need to someway close the file, without inserting all the code in a Try Catch block...
Next time the timer executes, it tries to access again the file and it is opened, so can''t add information.

What would you do?

Please help me.

Thanks in Advance.

推荐答案

您可以使用finally块关闭文件.

试试
{
//打开
}
赶上
{
//哎呀
}
终于
{
//关闭,这总是被调用.
}
You use the finally block to close the file.

try
{
// open
}
catch
{
// oops
}
finally
{
// close, this is always called.
}


我认为您追求的是

I think what you are after is

timer_fired_event method 
{ 
try 
{ 
open_log_file 
call_method_with_other_logic()
} 
catch 
// these should be fatal exceptions throw either by the file open, 
//or in the called method
{ 
} 
finally
{ 
close_log_file 
} 

private void call_method_with_other_logic()
{ 
// this may or may not write to open log file 
// this may or may not throw an exception 
// you may want to catch some exceptions here and handle them if appropriate or // let them bubble up the call stack 
}


鉴于您正在使用计时器,因此在多线程环境中工作,很可能会引发IO异常,因此您将必须捕获它们并处理它们-在不知道应用程序范围的情况下,仅关闭文件总是正确的做法吗?

您可能需要在计时器触发的代码中添加一些同步锁定,以防止多次尝试打开文件.
Given that you are using a timer and therefore working in a multi-threaded environemnt, it is very likely that you are going to get IO exceptions thrown, so you are going to have to catch them and handle them - without knowing the scope of your application, is just closing the file always the right thing to do?

You may want to add some sync locking in your timer fired code to also prevent multiple attempts to open the file.


这篇关于异常后文件保持打开状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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