singleton messagebox
本文关键字:messagebox singleton | 更新日期: 2023-09-27 18:23:49
我正在编写一个应用程序,当连接出现问题时,我想弹出一个消息框并向用户显示错误。。。
为此,当程序抛出异常时,它将进入catch块,因为我想向用户显示以下消息:
catch (WebException ex)
{
if (!(ex.Message == "The operation has timed out."))
{
MessageBox.Show(ex.Message);
}
}
似乎程序会永远陷入这种困境,直到连接被修复,那么我应该怎么做才能一次在一个消息框上更新我的消息呢?
显示MessageBox
时,对其没有太多控制。我会使用另一个以模态模式显示的Form
。在显示之前,您可以启动一个单独的线程,并放置逻辑来监视连接。重新建立后,通知消息表单并关闭它。
您可以使用以下内容
public static class FailureMessagebox
{
private static bool _hasBeenSuccessful = true;
public static void ShowIfFailure(Action someAction)
{
try
{
someAction();
_hasBeenSuccessful = false;
}
catch (Exception err)
{
if (_hasBeenSuccessful)
MessageBox.Show(ex.Message);
_hasBeenSuccessful = false;
throw;
}
}
}
示例用法:
try
{
WebResponse response;
FailureMessagebox.ShowIfFailure(() => response = webRequest.GetResponse());
}
catch (WebException err)
{
//handle the exception here.
}