How can I create events in a safer way?

4

I'm creating events according to the code below, however it seems to be a slightly dangerous way, since if there is no event cancellation it will accumulate with every "trigger" of the event, ie if it occurs three times on the fourth time it will run four times and not just one. How can I rewrite the code so that the event cancellation does not depend on a "= -"?

 private static MainWindow _mainWindow;
    public static void Start(MainWindow mainWindow)
    {
        _mainWindow = mainWindow;
    }

    public static void AtivaProgressBar()
    {
        _mainWindow.ProgressBar1.IsIndeterminate = true;

        Suporte.Processo();

        Suporte.OnProcessoLongo += Suporte_OnProcessoLongo;
    }

    static void Suporte_OnProcessoLongo()
    {

        _mainWindow.StackPanel.Dispatcher.Invoke((Action)(() =>
        {
            _mainWindow.ProgressBar2.IsIndeterminate = true;

            MessageBox.Show("Call me");

            Suporte.OnProcessoLongo =- Suporte_OnProcessoLongo;

        }));
    }

public class Suporte
{
    public delegate void ProcessoLongo();

    public static event ProcessoLongo OnProcessoLongo;

    public static void Processo()
    {
        Task.Factory.StartNew((() => {

            Thread.Sleep(3000);

            RaiseProcessoLongo();
        }));
    }

    static void RaiseProcessoLongo()
    {
        if (OnProcessoLongo != null)
            OnProcessoLongo();
    }
}
    
asked by anonymous 29.09.2015 / 16:41

2 answers

3

The easiest way is to remove an event notifier from an event and then add it again, so it will not be duplicated. It's okay to remove the notification without adding it before.

    public static void AtivaProgressBar()
    {
        _mainWindow.ProgressBar1.IsIndeterminate = true;

        Suporte.Processo();

        Suporte.OnProcessoLongo -= Suporte_OnProcessoLongo;
        Suporte.OnProcessoLongo += Suporte_OnProcessoLongo;
    }
    
22.02.2016 / 14:58
0

DDD - Domain Events

There is a specific design pattern for this issue, it is called DDD - Domain Events.

This pattern is intended for layers to communicate by events.

What is it?

"Domain Events are events that make sense for the domain, that is, things that need to happen when a particular action occurs, for example a transport system, we might have events such as" cargo delivered "," "Or" separation charge. "

And explaining the introduction a bit, we say that Domain Events is a kind of message that describes something that happened in the past that is of business interest, we use this to separate all the technical concerns of the domain, writing are all encapsulated in commands in the form of submissions. "

How to implement?

Follow the tutorial

link

    
15.03.2016 / 16:35