2012-04-03 6 views
1
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? 

    } 

ボタンを「送信」(スレッドの完了後)にリセットします。しかし、フォームは待つべきではありません。これは可能ですか?これはフォームを待っているのではなく、スレッドの完了通知が必要です

+0

うわー、9時間。 http://stackoverflow.com/questions/2773479/how-to-check-if-thread-finished-execution –

答えて

1

あなたは、これは、よりエレガントにBackgroundWorkerクラスを使用して行うことができます。 Buttonの

XAML:

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

コード:

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" }); 
     } 

    } 
+0

おかげで、詳細な応答を充てる: は、このリンクを参照してください。しかし、どのように '** send.Image **'はここで呼び出されますか? – SHRI

+0

RunWorkerAsync()メソッド呼び出しで引数を渡すことができます。私はそれを行う方法についてサンプルを更新しました。 –

2

ボタンをWindow/UserControlクラスのメンバにします(XAMLにNameを付けます)。スレッドが最終的に終了すると、スレッドメソッドから戻る前に、次の操作を行います。

myButton.Dispatcher.BeginInvoke(
    (Action)(() => myButton.Content = "Send")); 
関連する問題