No overload for 'textBox1_TextChanged_1' matches delegate 'System.Threading.TimerCallback

StackOverflow https://stackoverflow.com/questions/23632992

  •  21-07-2023
  •  | 
  •  

I want to use System.Threading.Timer so that I can use this timer to call method "CreateThread" which is as follows.

public void CreateThread()
    {
        th1 = new Thread(ChangeLabel);
        th1.Start();
    }

I am getting error at line:

public void textBox1_TextChanged_1(object sender, EventArgs e)
    {
       TimerCallback tcb = new TimerCallback(CreateThread); //This line is showing error
    }

Can anybody please explain what is the problem?

有帮助吗?

解决方案

TimerCallback expects a state property in the delegate:

public void CreateThread(object state)
    {
        th1 = new Thread(ChangeLabel);
        th1.Start();
    }

MSDN:

public delegate void TimerCallback(
    Object state
)

其他提示

The problem is your method signature doesn't match with the TimerCallback delegate.It takes an object as parameter, but your method takes nothing.

If you look at the MSDN Documentation for the TimerCallback delegate, you will see that it has a signature of void TimerCallback(object).

The method you want the timer to call needs the same signature so that it will compile.

Something like this would fix it:

public void CreateThread()
{
    CreateThread(null);
}

private void CreateThread(object state)
{
    th1 = new Thread(ChangeLabel);
    th1.Start();
}

This would allow any existing callers of CreateThread() to remain unchanged, whilst giving you a method with the correct signature to call the method.

Alternatively, you could do the following by using a lambda:

public void textBox1_TextChanged_1(object sender, EventArgs e)
{
   TimerCallback tcb = new TimerCallback(() => CreateThread());
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top