2
 private void btnSend_Click(object sender, RoutedEventArgs e) { Button obj=(Button)sender; obj.Content="Cancel"; SendImage send = new SendImage(); Thread t = new Thread(send.Image); t.Start(); //run separate thread.(very long, 9 hours) //so dont wait. //but the button should be reset to obj.Content="Send" //Can I do this? } 

I want the button to be reset to "Send" (after completion of thread). But form should not wait. Is this possible?

1

2 Answers 2

2

You can do this more elegantly using the BackgroundWorker class.

XAML for the Button:

 <Button x:Name="btnGo" Content="Send" Click="btnGo_Click"></Button> 

Code :

 private BackgroundWorker _worker; public MainWindow() { InitializeComponent(); _worker = new BackgroundWorker(); _worker.WorkerSupportsCancellation = true; _worker.WorkerReportsProgress = true; } private void btnGo_Click(object sender, RoutedEventArgs e) { _worker.RunWorkerCompleted += delegate(object completedSender, RunWorkerCompletedEventArgs completedArgs) { Dispatcher.BeginInvoke((Action)(() => { btnGo.Content = "Send"; })); }; _worker.DoWork += delegate(object s, DoWorkEventArgs args) { Dispatcher.BeginInvoke((Action)(() => { btnGo.Content = "Cancel"; })); SendImage sendImage = args.Argument as SendImage; if (sendImage == null) return; var count = 0; while (!_worker.CancellationPending) { Dispatcher.BeginInvoke((Action)(() => { btnGo.Content = string.Format("Cancel {0} {1}", sendImage.Name, count); })); Thread.Sleep(100); count++; } }; if (_worker.IsBusy) { _worker.CancelAsync(); } else { _worker.RunWorkerAsync(new SendImage() { Name = "Test" }); } } 
Sign up to request clarification or add additional context in comments.

2 Comments

thanks allot for detailed reply. But How 'send.Image' will be called here?
You can pass arguments with the RunWorkerAsync() method call. I have updated the sample on how to do that.
2

Make the Button a member of your Window/UserControl class (by giving it a Name in XAML). When the thread eventually finishes, do this before returning from the thread method:

myButton.Dispatcher.BeginInvoke( (Action)(() => myButton.Content = "Send")); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.