Generic method for updating Cross-thread error form

Asked

Viewed 22 times

2

I have a form where you need to do several updates using the thread-safe calls for Windows Forms controls

Snippets of code that do this repeat several times. Trying to refactor I created a kind of general method for updating.

I have a class to register the methods that will be used within the general method :

public class ListOfUpdateMethods
{
    public delegate void Metodo();
    private List<Metodo> MetodosPreAtualizacao;
    private List<Metodo> MetodosAtualizacao;

    public ListOfUpdateMethods()
    {
        this.MetodosPreAtualizacao = new List<Metodo>();
        this.MetodosAtualizacao = new List<Metodo>();
    }

    public void AddMetodosPreAtualizacao(Metodo m)
    {
        this.MetodosPreAtualizacao.Add(m);
    }

    public void AddMetodosAtualizacao(Metodo m)
    {
        this.MetodosPreAtualizacao.Add(m);
    }

    public void ExecutaMetodosPreAtualizacao()
    {
        foreach (var m in this.MetodosPreAtualizacao)
            m();
    }

    public void ExecutaMetodosAtualizacao()
    {
        foreach (var m in this.MetodosAtualizacao)
            m();
    }
}

It’s the method itself :

//Metodo geral para atualizar todos os Controles que forem necessários 

    private void UpdadeControl(ListOfUpdateMethods list, Control control)
    {
        //Executa metodos necessários antes de atualizar o controle
        list.ExecutaMetodosPreAtualizacao();

        if (control.InvokeRequired)
        {
            var up = new Updates(UpdadeControl);
            Invoke(up, new object[] { list, control });
        }
        else
        {
            //Executa metodos necessários para atualizar o controle
            list.ExecutaMetodosAtualizacao();

        }
    }

When I intend to update some control, what I do is :

ListOfUpdateMethods VariavelDeInstancia = new ListOfUpdateM ethods();
UpdateStopXRayTimer.AddMetodosAtualizacao(MetodoComInstrucoesQUeAtualizaOControle);
UpdadeControl(VariavelDeInstancia, ControleASerAtualizado);

However, when Methodocominositionsystematization is called a cross-theadins access exception occurs. That is, the method is not executed on the main treading.

An example of what it would have within this method would be :

void MetodoComInstrucoesQUeAtualizaOControle()
{
   ControleASerAtualizado = "Texto a ser add a um controle";
}

Does anyone have any tips on how to solve the problem described ?

No answers

Browser other questions tagged

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