Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Posts Tagged ‘Using BackgroundWorker with WPF’

Using BackgroundWorker with WPF

Posted by Viral Sarvaiya on March 26, 2012


When one process take so much long time and UI thread needs to stay responsive while process is running, the most common method to place a long running process on a separate thread.

In WPF there are mostly use technique is  Backgroundworker. Backgroundworker is mostly use in multithreading applications.

Here I show a small example of backgroundworker.

In WPF application I call WCF service function directly not asynchronies, so that function take time get response and at that time user can’t see what happen. so we have to integrate busyindicater while service call.

Busyindicater comes with WPF extended toolkit.

private void OKButton_Click(object sender, RoutedEventArgs e)
{
MyService myservice = new MyService();
MyServiceResponse Myserviceresponce = new MyServiceResponse();
Myserviceresponce = myservice.CallMyFunction(int Para1, string para2);
}

here when user click to OK Button, CallMyFunction() take so much long time and end user confuse what to do at that time and he/she click more than one time to that button and application will crashed.

so we put busy indicator in our code and calling this function asynchronies with backgroundworker.

<extToolkit:BusyIndicator x:Name="_busyIndicator" >
<Grid>
....
</Grid>
</extToolkit:BusyIndicator>

and in CS page

private void OKButton_Click(object sender, RoutedEventArgs e)
{
_busyIndicator.IsBusy = true;

MyServiceResponse Myserviceresponce = new MyServiceResponse();

BackgroundWorker worker = new BackgroundWorker();
worker.RunWorkerAsync();

//this is where the long running process should go
worker.DoWork += (o, ea) =>
{
MyService myservice = new MyService();
Myserviceresponce = myservice.CallMyFunction(int Para1, string para2);
};

worker.RunWorkerCompleted += (o, ea) =>
{
_busyIndicator.IsBusy = false;

//Continue other statment of this function...
};
}

So this will display busyindicator while service call complete.
Hope this will helps you.
Thanks.

Advertisements

Posted in .Net, Visual Studio, WCF Services, WPF | Tagged: , , , , , , , , | 2 Comments »

 
%d bloggers like this: