开发者

General approach for posting business logic status messages to UI?

开发者 https://www.devze.com 2022-12-23 05:47 出处:网络
I have been struggling with this question for awhile now, and I haven\'t reached a conclusion.I\'m not typically a UI programmer, so forgive 开发者_JAVA技巧the noobishness.

I have been struggling with this question for awhile now, and I haven't reached a conclusion. I'm not typically a UI programmer, so forgive 开发者_JAVA技巧the noobishness.

I'm writing a typical application with a UI layer (WPF) and a business layer. I want to post status messages to the UI from the business layer (perhaps deep within the business layer), but I don't want the business layer to have any knowledge of the UI. Is there a generally accepted pattern for this?

I was thinking to have a message queue of some sort to which the business layer posts status messages, and have the view model of the UI subscribe to that queue and intercept messages from the queue and route them to the UI. Is that a good approach? Is there somewhere else I should start?

Thank you.


I think that's a good approach in general. I would create an interface for your message provider that publishes an event when a message is received (Where Message is the message type you want):

public class MessageReceivedEventArgs : EventArgs
{
    public MessageReceivedEventArgs(Message message)
        : base()
    {
        Message = message;
    }

    public Message Message { get; set; }
}

public delegate void MessageRecievedHandler(object sender, MessageReceivedEventArgs e);

public interface IMessageProvider
{
    event MessageRecievedHandler MessageReceived;
    void Start();
    void Stop();
    bool IsRunning { get; }
}

public abstract class MessageProviderBase : IMessageProvider
{
    public event MessageRecievedHandler MessageReceived;

    public MessageProviderBase()
    {}

    protected void OnMessageReceived(MessageReceivedEventArgs e)
    {
        if (MessageReceived != null)
        {
            MessageReceived(this, e);
        }
    }

    public abstract void Start();
    public abstract void Stop();

    public abstract bool IsRunning { get; }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消