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?

SHRI
  • 2,406
  • 6
  • 32
  • 48

2 Answers2

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"));
Clemens
  • 123,504
  • 12
  • 155
  • 268
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" });
      }

    }
Magnus Johansson
  • 28,010
  • 19
  • 106
  • 164