Problem with MyThread and Timer Control

I have a method that is called in the second thread:

    public byte[] ReadAllBytesFromStream(Stream input)
    {
        clock.Start();

        using (...)
        {
            while (some conditions) //here we read all bytes from a stream (FTP)
            {
                ...
 (int-->)       ByteCount = aValue;
                ...
             }
            return .... ;
        }
    }

    private void clock_Tick(object sender, EventArgs e)
    {
        //show how many bytes we have read in each second
        this.label6.Text = ByteCount.ToString() + " B/s"; 
    }

The problem is that the clock is on, but it is not ticking. Why?

Update:

Tick ​​event added correctly, Interval property set to 1000.

I put Timer Control in a form in Design View.

+3
source share
6 answers

The problem is that you include your timer in a second thread, and that thread has no message pump.

Windows SetTimer. , API SetTimer. WM_TIMER , . Tick.

, , WM_TIMER . , , , WM_TIMER , . , , this , , ( , ) :

public byte[] ReadAllBytesFromStream(Stream input)
{
    if(this.InvokeRequired)
    {
        this.Invoke(new MethodInvoker(clock.Start));
    }
    else
    {
        clock.Start();
    }

    using (...)
    {
        while (some conditions) //here we read all bytes from a stream (FTP)
        {
            ...
 (int-->)   ByteCount = aValue;
            ...
         }
        return .... ;
    }
}

private void clock_Tick(object sender, EventArgs e)
{
    this.label6.Text = ByteCount.ToString() + " B/s"; //show how many bytes we have read in each second
}
+4

Tick , . :

clock.Tick += this.clock_Tick;
+3

. , ( ) "clock_Tick" , :

private void clock_Tick(object sender, EventArgs e)
{
    // InvokeRequired will be true on every thread EXCEPT the UI thread
    if (label6.InvokeRequired)
    {
        // Issue an asynchoronous request to the UI thread to perform the update
        label6.BeginInvoke(new MethodInvoker(this.clock_Tick), sender, e);
    }
    else
    {
        // Actually do the update
        label6.Text = ByteCount.ToString() + " B/s";
    }
}

WinForms.. WPF , .

: http://weblogs.asp.net/justin_rogers/pages/126345.aspx

!

+1

Interval ?

0

, , Timer Timer clock_Tick.

0

You may have a conflict between "System.timer" and "windows.form.timer". System.timer runs in a separate thread, and form.timer runs in the main thread, so in .designer.cs change the "timer" to "System.windows.form.timer", then it should work

0
source

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


All Articles