vendredi 27 novembre 2020

How to efficiently make a single instance for attaching events and share between two classes in .Net Standard

I'm working on a .Net Standard project and implementing some events from a third-party SDK.
As comments in the SDK, only one single instance of event args can be sent back.
Well, when all events are attached in one class, works fine.

Now I need to separate the class into two pages (classes).
Those events will be triggered on either of the pages.
But I cannot guarantee the initial order of those two pages, or one page might never be initialized.

So what I've done here (which works fine for now) is to share the properties in a global class and attach the events based on a boolean flag:

public class MainClass()
{
    public bool AttachFlag { get; set; } = false;
    public List<Obj> ObjList { get; set; } 
}
public class Page1() 
{
    private IProgress<ObjEventArgs> localChanged;

    public Page1()
    {
        if (!AttachFlag)
        {
            localChanged = new Progress<ObjEventArgs>(this.ObjUpdated);
            this.objManager.ObjChanged += (sender, e) => localChanged.Report(e.Object);

            AttachFlag = true;
        }
    }

    private void ObjUpdated(ObjEventArgs e)
    {
        //Update ObjList from e
    }
}
public class Page2()    //same logic as Page1 class
{
    private IProgress<ObjEventArgs> localChanged;

    public Page2()
    {
        if (!AttachFlag)
        {
            localChanged = new Progress<ObjEventArgs>(this.ObjUpdated);
            this.objManager.ObjChanged += (sender, e) => localChanged.Report(e.Object);

            AttachFlag = true;
        }
    }

    private void ObjUpdated(ObjEventArgs e)
    {
        //Update ObjList from e
    }
}

I wonder if any suggestion to make this logic more efficient and maintainable.

Cheers

Aucun commentaire:

Enregistrer un commentaire