Insert data into a real-time text box with Timer

Asked

Viewed 207 times

0

I’m using timer as follows:

System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 1000;
aTimer.Enabled = true;

In the method OnTimedEvent I’ll tell you what:

var auditoria = auditoriaBll.Retorna_Auditoria();

foreach (var item in auditoria)
{
    //menu e sub menu (categorias)
    if (item.Tabela.Equals("menus")) 
    {
        txtRelatorio.Text = andamento;
    }
}

The following error happens:

Invalid threaded operation: txtRelatory control accessed from a thread that is not the one in which it was created.

1 answer

1


Basically, you can only access elements created in thread within this same thread. To solve, you need to use the method Invoke

var auditoria = auditoriaBll.Retorna_Auditoria();

foreach (var item in auditoria)
{
    //menu e sub menu (categorias)
    if (item.Tabela.Equals("menus")) 
    {
        this.Invoke(new MethodInvoker(() => txtRelatorio.Text = andamento));
    }
}
  • this Invoke method is a delegate type? if it is, I have to create?

  • Method Invoke is of class Control (see in the documentation, I Linkei in the reply). The method receives a delegate, but I did it with a lambda expression because it’s much simpler.

  • ;The following error appears: Severity Code Description Project Error CS1660 Cannot Convert lambda Expression to type 'Delegate' because it is not a delegate type

  • I’ve already edited the answer... In fact, I was going to get better to give you some tips, but your question is duplicated.

Browser other questions tagged

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