C# Threading using invoke, freezing the form

徘徊边缘 提交于 2019-11-30 14:19:08
sumeet

This solution works ! Have checked it.

The problem is you keep telling the UI thread to change the Text, but never letting it have time to show you the updated text. To make your UI show the changed text, add the Application.DoEvents line like this :

textBox.Text += text;
Application.DoEvents();

p.s. : Remove the else block of your If / Else loop, it is redundant, and also as pointed by others there is not any use of creating those 2 Threads as all they are doing is post the message on the UI Thread itself.

You're still performing a single-threaded task, just re-launching it on the UI thread if needed.

for (int i = 0; i < 500; i++){
    string text = ""+i;
    textBox.BeginInvoke((MethodInvoker)delegate()
            {
                textBox.Text += text;
            });
}

The problem is that you're starting a new thread, and then that new thread is doing nothing except adding one new task for the UI thread to process that does a lot of work. To keep your form responsive you need to have time where the UI thread is doing nothing, or at least not spending a significant amount of time doing any one task.

To keep the form responsive we need to have lots of little BeginInvoke (or Invoke) calls.

private void writeText(TextBox textBox, string text)
{
    for (int i = 0; i < 500; i++)
    {
        Invoke(new MethodInvoker(() =>
        {
            textBox.Text += text;
        }));
    }
}

By having lots of little invoke calls it allows things like paint events, mouse move/click events, etc. to be handled in the middle of your operations. Also note that I removed the InvokeRequired call. We know that this method will be called from a non-UI thread, so there's no need for it.

You're defeating the purpose of using threads.

All your thread does is tell the UI thread to execute some code using BeginInvoke().

All of the actual work happens on the UI thread.

Either you're doing data processing or you're just trying to animate the UI.

For data processing you should do all the heavy lifting on a background thread and only update the UI occasionally. In your example a TextBox is particularly troublesome in this regard, as you're adding data to the underlying data model several hundred times and the UI element (a TextBox) takes longer to render each time. You must be careful about how often to update the UI so that processing for UI updates does not overwhelm data model updates. TextBoxes are nasty like that.

In the example below, a flag set during the paint event ensures that additional UI updates aren't queued until the TextBox has finished painting the last update:

string str = string.Empty;
public void DoStuff()
{
    System.Threading.ThreadPool.QueueUserWorkItem(WorkerThread);
}

void WorkerThread(object unused)
{
    for (int i = 0; i < 1000; i++)
    {
        str += "0";
        if (updatedUI)
        {
            updatedUI = false;
            BeginInvoke(new Action<string>(UpdateUI), str);
        }
    }
    BeginInvoke(new Action<string>(UpdateUI), str);
}

private volatile bool updatedUI = true;
void textbox1_Paint(object sender, PaintEventArgs e) // event hooked up in Form constructor
{
    updatedUI = true;
}

void UpdateUI(string str)
{
    textBox1.Text = str;
}

On the other hand if UI animation is your goal then you probably ought to be using something other than a TextBox. It's just not designed to handle updates so frequently. There might be some optimizations to text rendering you could make for your specific use case.

You must never use a string in high volume applications. UI or not. Multi-threading or not.

You should use StringBuilder to accumulate the string. and then assign

tb.Text = sb.ToString();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!