我有一个带有各种HW接口的多线程wpf应用程序。
我想对可能发生的几次硬件故障作出反应。
例如:
其中一个接口是温度传感器,我希望从某个温度。将出现一个meesage并通知用户它发生了。
我提出了以下设计:
/// <summary>
/// This logic reacts to errors that occur during the system run.
/// The reaction is set by the component that raised the error.
/// </summary>
public class ErrorHandlingLogic : Logic
{
}
上述类将使用ErrorEventData,其中包含有关发生的错误的所有信息。
public class ErrorEventData : IEventData
{
#region public enum
public enum ErrorReaction
{
}
#endregion public enum
#region Private Data Memebers and props
private ErrorReaction m_ErrorReaction;
public ErrorReaction ErrorReactionValue
{
get { return m_ErrorReaction; }
set { m_ErrorReaction = value; }
}
private string m_Msg;
public string Msg
{
get { return m_Msg; }
set { m_Msg = value; }
}
private string m_ComponentName;
public string ComponentName
{
get { return m_ComponentName; }
set { m_ComponentName = value; }
}
#endregion Private Data Memebers and props
public ErrorEventData(ErrorReaction reaction, string msg, string componenetName)
{
m_ErrorReaction = reaction;
m_Msg = msg;
m_ComponentName = componenetName;
}
}
上面的ErrorHandlingLogic将决定如何处理从应用程序的各个组件发送给他的ErrorEventData。
如果需要,它将被转发到GUI以向用户显示消息。
所以您认为这是一个好的设计?
感谢, Adiel。
答案 0 :(得分:3)
然而,就设计而言,这似乎是公平的,我可能会选择带有自定义事件参数的标准事件。
以下是一个例子:
public interface IEventData
{
ErrorReaction Reaction { get; }
string Message { get; }
ComponentName { get; }
}
public class HardwareChangeEventData : IEventData
{
public HardwareChangeEventData(ErrorReaction reaction, string msg, string componentName)
{
Reaction = reaction;
Message = msg;
ComponentName = componentName;
}
public ErrorReaction Reaction { get; private set; }
public string Message { get; private set; }
public ComponentName { get; private set; }
}
....
// introduce a base class so all hardware components can raise the event
public class HardwareComponent
{
public delegate void HardwareChangedEventHandler(IEventData ed);
public event HardwareChangedEventHandler HardwareChanged;
//event-invoking method that derived classes can override.
protected virtual void OnHardwareChanged(IEventData ed)
{
HardwareChangedEventHandler handler = HardwareChanged;
if (handler != null)
{
handler(this, ed);
}
}
}
public class TemperatureGauge : HardwareComponent
{
public void Monitor()
{
// example logic
while (...)
{
if (Temperature < LowThreshold)
{
IEventData ed = new HardwareChangeEventData(ErrorReaction.IncreaseTemp, "Temperature too low!", "TemperatureGauge");
OnHardwareChanged(ed);
}
}
}
public override OnHardwareChanged(IEventData ed)
{
// do something with ed internally (if applicable)
// forward event on to base so it can be passed out to subscribers
base.OnHardwareChanged(ed);
}
}
答案 1 :(得分:1)
以上代码看起来不错。
但是为了通知不同的组件,我会说寻找观察者模式(Event / Deleagte)
答案 2 :(得分:0)
如果您要在WPF中处理错误,为什么不使用验证器呢? see this acticle