Easy thread programming

I started playing streams in C #, but now I need help, here is my code:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        DoCount();
    }
    public void DoCount()
    {
        for (int i = 0; i < 100; i++)
        {
            objTextBox.Text = i.ToString();
            Thread.Sleep(100);
        }
    }
}

its a simple win form with a text box, I want to see a “count”, but as you see in my code, the text box shows me 99, it counts to 99, and then appears .. I’ll think I have to manage this in a new thread but don’t know how to do it.

+3
source share
9 answers

Use BackgroundWorker . MSDN has a BackgroundWorker Overview .

Here is an example of what your code looks like:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
        for (int i = 0; i < 100; i++)
        {
            backgroundWorker.ReportProgress(i);
            Thread.Sleep(100);
        }
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        textBox1.Text = e.ProgressPercentage.ToString();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }
}

Other notes:

+8

, :

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        DoCount();
    }
    public void DoCount()
    {
        Thread t = new Thread(new ThreadStart(delegate
        {
           for (int i = 0; i < 100; i++)
           {
               this.Invoke((Action) delegate { objTextBox.Text = i.ToString(); });
               Thread.Sleep(1000);
           }
        }));
        t.IsBackground = true;
        t.Start();
    }
}

  • Thread BackgroundWorker
  • .
  • IsBackground true, , .
+7

SynchronizationContext.

, :

public partial class Form1 : Form
{
    private SynchronizationContext c;
    private Thread t;
    private EventWaitHandle pause =
        new EventWaitHandle(false, EventResetMode.ManualReset);

    public Form1()
    {
        this.InitializeComponent();
        this.c = SynchronizationContext.Current;
    }

    private void Form1Activated(object sender, EventArgs e)
    {
        this.t = new Thread(new ThreadStart(delegate
        {
            this.pause.Reset();
            while (this.t.IsAlive && !this.pause.WaitOne(1000))
            {
                this.c.Post(
                    state => this.label1.Text = DateTime.Now.ToString(),
                    null);
            }
        }));
        this.t.IsBackground = true;
        this.t.Start();
    }

    private void Form1Deactivate(object sender, EventArgs e)
    {
        this.pause.Set();
        this.t.Join();
    }

    /// <summary>
    /// Button1s the click.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    private void Button1Click(object sender, EventArgs e)
    {
        this.Close();
    }
}
+1

, - , System.Windows.Forms.Timer . - 1 ( ), - .

+1

DoCount , ThreadPool.QueueUserWorkItem(DoCount). DoCount . ( , , , .)

, .

, , :

if (this.textBox1.InvokeRequired)
{   
    SetTextCallback d = new SetTextCallback(SetText);
    this.Invoke(d, new object[] { text });
}

. http://msdn.microsoft.com/en-us/library/ms171728(VS.80).aspx.

0

Thread.Sleep :

this.Update();
0

, . InvokeRequired ProgressChanged. :

using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace tester
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        /// <summary>
        /// This delegate enables asynchronous calls for setting the text property on a control.
        /// </summary>
        delegate void SetTextCallback(string status);

        private void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
        {
            for (var i = 0; i < 100; i++)
            {
                backgroundWorker1.ReportProgress(i);
                Thread.Sleep(100);
            }
        }

        private void BackgroundWorker1ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (label1.InvokeRequired)
                Invoke(new SetTextCallback(SetLabelText), new object[] { e.ProgressPercentage.ToString()});
            else
                SetLabelText(e.ProgressPercentage.ToString());
        }

        private void SetLabelText(string text)
        {
            label1.Text = text;
        }
    }
}
0

, - , , .

this.Update(). , , . , ( ).

- Application.DoEvents(). , ProcessMessages . , Windows , , , , .. Windows . , , . .

Application.DoEvents() , 100 . ( ), .

for (int i = 0; i < 100; i++)
{
    objTextBox.Text = i.ToString();
    Application.DoEvents();
    Thread.Sleep(100);
}
0
source

Here is my snapshot with a simple example:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Action countUp = this.CountUp;
        countUp.BeginInvoke(null, null);
    }

    private void CountUp()
    {
        for (int i = 0; i < 100; i++)
        {
            this.Invoke(new Action<string>(UpdateTextBox), new object[] { i.ToString() });
            Thread.Sleep(100);
        }
    }

    private void UpdateTextBox(string text)
    {
        this.textBox1.Text = text;
    }
}
0
source

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


All Articles