我想在數據網格中顯示臨時文件,因此這是一個長期的過程,我在我的C#.net WPF應用程序中使用後臺工作。後臺工作人員在WPF中無法正常工作
我的代碼是
private System.ComponentModel.BackgroundWorker _background = new System.ComponentModel.BackgroundWorker();
private void button1_Click(object sender, RoutedEventArgs e)
{
_background.RunWorkerAsync();
}
public MainWindow()
{
InitializeComponent();
this._background.DoWork += new DoWorkEventHandler(_background_DoWork);
this._background.RunWorkerCompleted += new
RunWorkerCompletedEventHandler(_background_RunWorkerCompleted);
this._background.WorkerReportsProgress = true;
_background.WorkerSupportsCancellation = true;
}
void _background_DoWork(object sender, DoWorkEventArgs e)
{
this.Dispatcher.Invoke((Action)(() =>
{
try
{
FileInfo[] files = new
DirectoryInfo(System.IO.Path.GetTempPath()).GetFiles();
foreach (FileInfo fi in files)
{
if (fi != null)
{
dataGrid1.Items.Add(fi);
}
}
}
catch { }
}));
}
void _background_RunWorkerCompleted(object sen, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("Cancelled");
}
else if (e.Error != null)
{
MessageBox.Show("Exception Thrown");
}
}
所有的代碼運行,但是當數據網格是裝載意味着我的UI做程序運行時沒有響應它掛起。
在上述情況下需要做些什麼修改才能順利運行後臺工作?
除此之外,如果我想添加一個ProgressBar,並與此應用程序一起進步,那我該怎麼辦?
謝謝你