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 :(得分:2)
使Button成为Window / UserControl类的成员(通过在XAML中为其提供Name
)。当线程最终完成时,在从线程方法返回之前执行此操作:
myButton.Dispatcher.BeginInvoke(
(Action)(() => myButton.Content = "Send"));
答案 1 :(得分:1)
您可以使用BackgroundWorker类更优雅地完成此任务。
按钮的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" });
}
}