The Silverlight/WPF BackgroundWorker class provides an easy way to run time-consuming operations on a background thread. The BackgroundWorker class enables you to check the state of the operation and it lets you cancel the operation.
When you use the BackgroundWorker class, you can indicate operation progress, completion, and cancellation in the Silverlight/WPF user interface. For example, you can check whether the background operation is completed or canceled and display a message to the user.
OutPut:
When you use the BackgroundWorker class, you can indicate operation progress, completion, and cancellation in the Silverlight/WPF user interface. For example, you can check whether the background operation is completed or canceled and display a message to the user.
XAML code in WPF for the same is here..
<Window x:Class="WpfDigital.BackGround"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BackGround" Height="300" Width="300">
<StackPanel>
<Button Content="Thread Start" Width="75" Click="Thread_Click"/>
<TextBlock x:Name="tbProgress" TextWrapping="Wrap" />
<Button Content="Cencel" Width="75" Click="Cancel_Click"></Button>
<Button Content="Other functionality is working" Width="75" Click="Other_Click"></Button>
</StackPanel>
</Window>
CS file of XAML
using System.Windows;
using System.ComponentModel;
namespace WpfDigital
{
public partial class BackGround : Window
{
BackgroundWorker myWorker = new BackgroundWorker();
public BackGround()
{
InitializeComponent();
myWorker.WorkerReportsProgress = true;
myWorker.WorkerSupportsCancellation
= true;
myWorker.DoWork += myWorker_DoWork;
myWorker.RunWorkerCompleted +=
myWorker_RunWorkerCompleted;
myWorker.ProgressChanged +=
myWorker_ProgressChanged;
}
void myWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
tbProgress.Text =
e.ProgressPercentage.ToString() + "%";
}
void myWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs
e)
{
if (e.Cancelled)
{
tbProgress.Text = "Cancelled";
}
else if (!(e.Error == null))
{
tbProgress.Text = "Error " +
e.Error.Message;
}
else
{
tbProgress.Text = "DONE";
}
}
void myWorker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 10; i++)
{
if (myWorker.CancellationPending)
{
e.Cancel = true;
return;
}
else
{
System.Threading.Thread.Sleep(1000);
myWorker.ReportProgress(i *
10);
}
}
}
private void Thread_Click(object sender, RoutedEventArgs e)
{
myWorker.RunWorkerAsync();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
if (myWorker.WorkerSupportsCancellation == true)
{
myWorker.CancelAsync();
}
}
private void Other_Click(object sender, RoutedEventArgs e)
{
System.Windows.Forms.MessageBox.Show("yes its working fine with background");
}
}
}
No comments:
Post a Comment