0
How do I close the Window after the thread runs ? This error is given: System.Invalidoperationexception: 'The call thread cannot access this object because it belongs to a different thread.'
Progressbar:
<Grid>
<ProgressBar Width="250" Height="35" Minimum="0" Maximum="100"
Value="{Binding WorkerState}"></ProgressBar>
</Grid>
Call from Window:
private void btnBuscarCep_Click(object sender, RoutedEventArgs e)
{
ProgressBar progressBar = new ProgressBar();
progressBar.ShowDialog();
}
Window:
public partial class ProgressBar : Window, INotifyPropertyChanged
{
private BackgroundWorker _bgWorker = new BackgroundWorker();
private int _workerState;
public event PropertyChangedEventHandler PropertyChanged;
public int WorkerState
{
get { return _workerState;}
set
{
_workerState = value;
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("WorkerState"));
}
}
}
public ProgressBar()
{
InitializeComponent();
DataContext = this;
_bgWorker.DoWork += (s, e) =>
{
for (int i = 0; i <= 100; i++)
{
System.Threading.Thread.Sleep(100);
WorkerState = i;
}
//O Erro Ocorre Aqui
Application.Current.MainWindow.Dispatcher.Invoke(() =>
{
Application.Current.MainWindow.Close();
});
};
_bgWorker.RunWorkerAsync();
}
}