我使用后台工作程序设置ProgressBar以显示下载文件时的进度。但BackgroundWorker的RunWorkerAsync()方法不会触发Do_Work事件。
/ ********** Window_Load *********** /
BackgroundWorker backgroundWorker1;
private void MainWindow_Load(object sender, RoutedEventArgs e)
{
backgroundWorker1=new BackgroundWorker();
backgroundWorker1.WorkerReportsProgress=true;
backgroundWorker1.DoWork +=new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.ProgressChanged +=new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
backgroundWorker1.RunWorkerCompleted +=new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
/ ****** ******* Button_Click /
void Button_Click(object sender, RoutedEventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
/ **** *********活动/
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
ProgressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("File download complete");
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//Code to download a file and setting progressbar time.
}
我是WPF的新手。任何帮助表示赞赏。
答案 0 :(得分:1)
您的代码看起来很好,但代码没有变化..想要了解以下内容
我建议你可以查看一下这篇文章: Multi-threading with the BackgroundWorker,这与你正在做同样的事情。你可能会找不到的东西。
答案 1 :(得分:1)
我设置了一个示例项目并完全使用了您的代码,并且没有任何编程错误,它在我身边完美运行。
确保您订阅了点击事件的按钮,这似乎没有被解雇
<Button Content="Button" HorizontalAlignment="Left" Margin="153,42,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
答案 2 :(得分:0)
试试这个例子,
<Button Content="Button" HorizontalAlignment="Left" Margin="165,58,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
private BackgroundWorker _backgroundWorker;
public MainWindow()
{
InitializeComponent();
_backgroundWorker = new BackgroundWorker();
_backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
_backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
_backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
_backgroundWorker.WorkerReportsProgress = true;
DataContext = this;
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
var eee = e.Result;
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
var progrss = e.ProgressPercentage;
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
int p=10;
for (int index = 0; index < p; index++)
{
object param = "something";
Thread.Sleep(100);
_backgroundWorker.ReportProgress(p, param);
Thread.Sleep(1000);
if (index == 10)
{
break;
}
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
_backgroundWorker.RunWorkerAsync();
}