Reputation: 503
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.
Upvotes: 2
Views: 130
Reputation: 564931
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();
}
Upvotes: 3
Reputation: 1183
You can use the solutions showed here:
How to update the GUI from another thread in C#?
Next time search a bit before asking.
Upvotes: 0
Reputation: 1
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()
.
Upvotes: 0
Reputation: 1064294
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.
Upvotes: 0
Reputation: 107062
You need to use Control.Invoke
to manipulate your form in it's own thread.
Upvotes: 0