简体   繁体   中英

Best way to pass data in between classes and forms?

Here is some background information on the project I am working on:

I am creating a spectral collection service MDI application that is used to collect spectral information. Inside my main form I have a hardware control class that orchestrates and controls a PLC control class and a spectral collection class. Inside the spectral collection and plc class are threads that run and continuously collect information about the spectrometer and plc respectively.

In addition, I am making the application so that a user can open a new child form and view all information about the system. I am trying to figure out a way for this system information to be seen from the child forms as they are continuously being updated.

I am having some ideas of using threads, timers, and/or events.

Use the Progress class to update the UI based on the progress of some background operation. The UI can create the object, defining how it plans to update the UI using the data, and then pass it to the non-UI operation which can provide the data without needing to know how the UI will be updated.

Here is a comparable implementation that you can use if you are using an earlier version of .NET:

public interface IProgress<T>
{
    void Report(T data);
}

public class Progress<T> : IProgress<T>
{
    SynchronizationContext context;
    public Progress()
    {
        context = SynchronizationContext.Current
            ?? new SynchronizationContext();
    }

    public Progress(Action<T> action)
        : this()
    {
        ProgressReported += action;
    }

    public event Action<T> ProgressReported;

    void IProgress<T>.Report(T data)
    {
        var action = ProgressReported;
        if (action != null)
        {
            context.Post(arg => action((T)arg), data);
        }
    }
}

If your constrained to using WinForms I recommend using the Smart Client Software Factory , or better yet use WPF and use Prism .

Both have the concept of sharing components around.

The following is by far the easiest way to pass information between classes.

#region Variables

private static bool bTest = false;

#endregion

#region Functions

public static bool getbTest()
{
    return bTest;
}

public static void setbTest(bool b)
{
    bTest = b;
}

#endregion

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM