.NET Desktop Generation

We are working on a Windows application that periodically launches operations that may take some time. We got the idea that these operations are performed on BackgroundWorker and write a quick WinForm for each operation, where you pass the necessary parameters to the form, the form connects to BackgroundWorker and calls the function, and the form displays the result (the progress bar moves, the text is filled with updates, etc. .d.).

Now, obviously, this form is a very cookie cutter. The only part that really differs between copies of the form is which method is called on which object. So, what we would like to do is make it general so that we can take a form, pass an object (or null for static calls?), A function name and an array of parameters, and make it just "go" from there. We were able to do this with Reflection. What we don’t like in this case is the lack of strong typing; things like misspelling a method call fall at runtime, and not at compile time. Is there anything available now that can make this more elegant and reliable? I heard about people who talked about things like Delegates and Expression Trees; but I'm not sure,that the former is applicable and still a little in the dark about the latter.

+3
source share
3 answers

Make a general form and pass it a delegate pointing to the method that it should run on BackgroundWorker would be a smart solution.

You can have a form constructor so that a common delegate is created as an argument (an action can be a good idea) and pass in a constructor a lambda expression that corresponds to the Action signature). Then, for the foreach action, you will only need to specify a suitable lambda expression.

Remember that a lambda expression can capture local variables, so you can call any logic that you did before and pass the same parameters.

+6
source

, . , Generics. , , .

+3

One thing you can do is create several different methods (one for methods without arguments, one for methods with one argument, etc.), for example:

public static void DisplayForm(Action action) {
    DisplayFormUsingInvoke(action);
}

public static void DisplayForm<T>(Action<T> action, T param) {
    DisplayFormUsingInvoke(action, param);
}

public static void DisplayForm<T,U>(Action<T,U> action, T param1, U param2) {
    DisplayFormUsingInvoke(action, param1, param2);
}

...

Then you can have a private method that actually does the job, similar to your current method, but not exposed to the client:

private static void DisplayFormUsingInvoke(Delegate d, params object[] parms) {
    // Edit this code to run it on the background thread, report progress, etc.
    d.DynamicInvoke(parms);
}

Then the client code will call one of the public methods, which will ensure that the correct number and types of arguments are specified.

+2
source

Source: https://habr.com/ru/post/1705988/


All Articles