What kind of function should I use?

Asked

Viewed 87 times

0

I’m trying to develop an application where when the value of a bool variable changes to false it must run a script. Should I use background_work to do this? If so, how should I use it? And if not, how should I do it?

  • 2

    Easier to do if you add the code to the question.

  • If you want this code ("script") to run in the background, yes, you could use the Backgroundworker component.

  • Why don’t you put it on setter this behavior? It would perfectly suit what you want. But without code or context it is difficult to try to help beyond that

  • 2

    @Jeffersonquesado Setters should not "run scripts" when a value is assigned to the property. If you really want to go through this way you can, but better implode INotifyPropertyChanged, this again would result in the use of events to solve the problem.

  • @Brunocosta understood that the notifier seems more elegant, but like Poger javeiro that I am, I did not understand why intercept the change in the value in setter and take action would be less recommended

  • 1

    @Jeffersonquesado Imagine that your "script" takes 5 minutes to run. Every time you change the value of the property you have to be stopped for 5 minutes? Even if you solve the issue by delegating the execution for example to the TheadPool would you actually advise this practice? You will probably be mixing business logic that has nothing to do with property value. Imagine that Voce has several processes to run, Voce will put everyone there? Not going, will implement the INotifyPropertyChanged as I suggested. Or at least should...

  • I voted to close because it seems that there was not much effort on the question. Adding a [mcve] could help.

Show 2 more comments

1 answer

3


Avoid doing this. Look for other alternatives first.

The reason for this recommendation comes from the simple fact that you must avoid, to the maximum extent possible, actively verifying a condition .

Active checks typically consume more resources (cpu) than passive checks, because you will eventually have to have a periodic check (for example within a loop) of a given state.

Passive checks, on the other hand, usually use techniques where there is a notification when a certain condition is met, meaning that there may not even be a check whether the condition is already met.

This is not to say that you should always use passive checks. Depending on the implementation passive checks may also have associated costs, such as context exchange It’s not exactly a cheap operation. But if you can choose between having the CPU to be used exhaustively to check a given state over a long period of time or doing a passive check you should choose the passive check.

You can resort to various passive verification techniques.

Using events (notification mechanism):

public class DadosDoEvento : EventArgs
{
    public string Dados { get; set; }
}

public class PublicadorDeEventos{
    public event EventHandler<DadosDoEvento> Evento; 

    protected virtual void OnEvento(OMeuEvento e)
    {
        Evento?.Invoke(this, e);
    }
    /*Um método qualquer que chame OnEvento */
}

var publicador = new PublicadorDeEventos();
publicador.Evento += (src, args) => Console.WriteLine(args.Dados);

Using events (synchronization mechanism):

public class PublicadorDeEventos{

    public ManualResetEvent Evento{ get { return new ManualResetEvent(false); } }

    /*Um método qualquer que chame Evento.Set();*/
}

var publicador = new PublicadorDeEventos();
publicador.Evento.WaitOne();

Using INotifyPropertyChanged:

I did not put this approach in my initial response because it is a specific scenario of the use of events (notification mechanism) and, in my opinion, it is not so simple to use. But this does not mean that it does not have its merit (maybe it is subject to another question), but I leave here an example:

public class Modelo : INotifyPropertyChanged
{
    private string _dados;
    public string Dados { 
        get {return _dados;}
        set {
            _dados = value;
            OnPropertyChanged(nameof(Dados));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(
        [CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

var modelo = new Modelo();
modelo.PropertyChanged += (sender, args) => {
    if (args.PropertyName == "Dados")
    {
        Console.WriteLine("Os dados mudaram vou executar o meu script aqui");
    }
} 

Which one should you use? I personally prefer to choose the first one. Usually the second alternative provides a harder-to-use API, and it doesn’t solve all cases. You need to be careful in choosing the proper synchronization mechanism and in special cases implement your own synchronization mechanism.

  • Cool, can publish an example of INotifyPropertyChanged ? Thank you

  • 1

    @Rovannlinhalis Made.

  • Thank you @Brunocosta

  • Thank you! @Brunocosta

Browser other questions tagged

You are not signed in. Login or sign up in order to post.