2

I have a form with text box and button. On click of button I'm creating a thread and invoking it for some operation. once the thread completes the invoked task, I want to update the text box with the result.

any one please assist me how can I achieve this without thread clash.

Sridhar
  • 463
  • 3
  • 15

5 Answers5

3

This is far simpler using .NET 4.0's Task class:

private void button_Click(object sender, EventArgs e)
{
    Task.Factory.StartNew( () => 
    {
         return DoSomeOperation();
    }).ContinueWith(t =>
    {
         var result = t.Result;
         this.textBox.Text = result.ToString(); // Set your text box
    }, TaskScheduler.FromCurrentSynchronizationContext());
}

If you're using .NET 4.5, you can simplify this further using the new async support:

private async void button_Click(object sender, EventArgs e)
{
    var result = await Task.Run( () => 
    {
         // This runs on a ThreadPool thread 
         return DoSomeOperation();
    });

    this.textBox.Text = result.ToString();
}
Reed Copsey
  • 539,124
  • 75
  • 1,126
  • 1,354
  • 2
    well, I'd call *dubious* on "simpler". It *might* be simpler if you just used `await`, which IIRC uses sync-context by default – Marc Gravell Dec 22 '12 at 22:39
  • @MarcGravell I find this far simpler than a thread with an invoke call in it, but that's personal preference. Good point on await - I'll add it as an option, too. – Reed Copsey Dec 23 '12 at 20:27
0

You need to use Control.Invoke to manipulate your form in it's own thread.

Vilx-
  • 101,209
  • 85
  • 267
  • 409
0

Simply, at the end of the thread operation:

/// ... your code here
string newText = ...

textBox.Invoke((MethodInvoker) delegate {
    textBox.Text = newText;
});

The Control.Invoke usage uses the message-queue to hand work to the UI thread, so it is the UI thread that executes the textBox.Text = newText; line.

Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
0

Use a BackgroundWorker, assign the task to the DoWork event, and update the text box with the RunWorkerCompleted event. Then you can start the task with RunWorkerAsync().

0

You can use the solutions showed here:

How to update the GUI from another thread in C#?

Next time search a bit before asking.

Community
  • 1
  • 1
geniaz1
  • 1,083
  • 1
  • 11
  • 16