You are developing an application by using Silverlight 4 and Microsoft .NET Framework 4.
You add a BackgroundWorker object named worker to the application. You also add a CheckBox control named checkBox and a TextBlock control named statusTextBlock.
You add the follo wing code segment. (Line numbers are included for reference only.)
01 public MainPage()
02 {
03 InitializeComponent();
04 worker.WorkerReportsProgress = true;
05 worker.DoWork += new DoWorkEventHandler(worker_DoWork);
06 worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
07 }
08 private void worker_DoWork(object sender, DoWorkEventArgs e)
09 {
10 for (int i = 0; i < 100; i++) {
11 bool isChecked = checkBox.IsChecked.HasValue && checkBox.IsChecked.Value;
12 ExecuteLongRunningProcessStep(isChecked);
13 worker.ReportProgress(i);
14 }
15 }
16 private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
17 {
18 statusTextBlock.Text = e.ProgressPercentage + “%”;
19 }
You attempt to run the application. You receive the following error message: “Invalid crossthread access.”
You need to ensure that worker executes successfully. What should you do?
A.
Replace line 11 with the following code segment.
var b = (bool )checkBox.GetValue(CheckBox.IsCheckedProperty);
bool isChecked = b.HasValue && b.Value;
B.
Replace line 11 with the following code segment. bool isChecked = false;
Dispatcher.BeginInvoke(() =>
{
});
isChecked = checkBox.IsChecked.HasValue && checkBox.IsChecked.Value;
C.
Replace line 18 with the following code segment.
statusTextBlock.SetValue(TextBlock.TextProperty, e.ProgressPercentage + “%”);
D.
Replace line 18 with the following code segment.
Dispatcher.BeginInvoke(() =>
{
});
statusTextBlock.Text = e.ProgressPercentage + “%”;