user2636982
user2636982

Reputation:

Create infinite loop without blocking form

It is possible to run infinite loop , but not block program or form with it?

For example i have one infinite loop

private void infLoop()
    {
      while(1<3)
      {
          textBox1.Text+="1";
          textBox1.Refresh();
      }
    }

Then on button I call it.

    private void button1_Click(object sender, EventArgs e)
    {
        infLoop();
    }

This wold block form , I cannot close it, move it, etc..

Is there some way who I run something like this in backward , and not block form with it?

Thanx

Upvotes: 1

Views: 3279

Answers (4)

Aron
Aron

Reputation: 15772

Simplest way to achieve this is by using async await. However this will run way too fast and will kill your computer.

private async void infLoop()
{
    while(1<3)
    {
        await Task.Yield();
        textBox1.Text+="1";
        textBox1.Refresh();
    }
}

What you are more likely wanting is this...

private async void infLoop()
{
    int i = 1;
    while(true)
    {
        await Task.Delay(TimeSpan.FromSeconds(1));
        textBox1.Text = i.ToString();
        textBox1.Refresh();
        i += 1;
    }
}

Upvotes: 4

Hermann Jung
Hermann Jung

Reputation: 7

You are talking about winforms? See BackgroundWorker

Upvotes: -2

Charlie
Charlie

Reputation: 4895

  1. Drag the backgroundworker control from tool box.
  2. double click on it
  3. add infinite loop in DoWorkEvent(autogenerated) add this code in the LoadFunction

        if (backgroundWorker1.IsBusy == false)
        {
            backgroundWorker1.RunWorkerAsync();
        }
    

    Backworkworker is a thread that runs in background to do heavy task and it runs GUI concurrently, without getting freeze .unless you use system calls etc

Upvotes: 0

insilenzio
insilenzio

Reputation: 938

Based on msdna, try this solution: maybe you'd have to adapt it for your needs.

This solution use a new Thread for setting textbox and a callback to avoid "the cross-thread InvalidOperationException" raised when you try to modify a form with the same thread which run the form itself.

    private void Form1_Load(object sender, EventArgs e)
    {
        System.Threading.Thread newThread = new System.Threading.Thread(new System.Threading.ThreadStart(this.ThreadProcSafe));
        newThread.Start();

    }

    private void ThreadProcSafe()
    {
        this.SetText();
    }

    private void SetText()
    {
        if (textBox1.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d);

        }
        else
        {
            while (1 < 3)
            {
                textBox1.Text += "1";
                textBox1.Refresh();
            }
        }
    }

Upvotes: 1

Related Questions