如果我在处理任务之前打开WaitCursor,然后将其恢复为默认值,我经常会得到这样的代码模式:
try {
Cursor.Current = Cursors.WaitCursor;
MyProcessingTask();
}
catch (Exception ex) {
Cursor.Current = Cursors.Default;
MessageBox.Show(ex.ToString());
}
finally { Cursor.Current = Cursors.Default; }我需要将Cursor.Current = Cursors.Default;放在catch块中,以便为MessageBox提供一个要使用的默认游标。
有没有一种更好的方法来编写这些代码,而不必编写两个Cursor.Current = Cursors.Default;语句?
发布于 2012-09-30 16:11:20
您可以创建一个可处理类并利用using语法糖,即:
class WaitingCursor : IDisposable
{
public WaitingCursor()
{
Cursor.Current = Cursors.WaitCursor;
}
public void Dispose()
{
Cursor.Current = Cursors.Default;
}
}用法:
try
{
using (var wcurs = new WaitingCursor())
{
MyProcessingTask();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}发布于 2012-09-30 16:11:51
您可以将try/finally块嵌套在try/catch块中:
try {
try {
Cursor.Current = Cursors.WaitCursor;
MyProcessingTask();
}
finally { Cursor.Current = Cursors.Default; }
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
}这是不是更好,可能会受到意见的影响。它减少了一些代码重复,但(在我看来)它看起来并不“熟悉”。有人可能会在6个月后看到这一点,并将其重构为熟悉的try/catch/finally结构(并丢失catch块中的光标更改)。
顺便说一句-在这种低级别捕获所有异常的一般模式通常是不受欢迎的。通过只显示Message来“处理”每一个可能的异常,你就失去了潜在的调试帮助。我通常建议您a)只处理代码实际上具有合理处理策略的特定异常,以及b)让所有其他异常传播给顶级异常处理程序,a)可能会显示一条消息,但b)还会记录异常的所有相关部分,包括调用堆栈等。
接受异常(就像这里)可能意味着应用程序不处于适合继续运行的状态,但会尝试这样做。使最终崩溃(如果发生)变得更加难以诊断。
发布于 2012-09-30 16:12:49
像这样怎么样?
Exception exception = null;
try
{
Cursor.Current = Cursors.WaitCursor;
MyProcessingTask();
}
catch (Exception ex)
{
exception = ex;
}
Cursor.Current = Cursors.Default;
if (exception!= null)
MessageBox.Show(exception.ToString());尽管这似乎是一个合理的解决方案,但我还是建议保留双游标设置,因为我更喜欢在Catch块中处理所有异常逻辑。
https://stackoverflow.com/questions/12659696
复制相似问题