Hi,
I want to show a loading icon in my wpf application when application is busy.
To implementing this I have taken a background worker and showing my loading image on BackgroundWorker_DoWork() event.
For Example: on save button click of wpf form process is something like this:
1. Have some ui controls like text box, lables and check boxes on the form.
2. On the save button I am sending the data in to database.
3. When save button is clicked then bgworker_dowork() is called and savedata() function is executed but as I getting the control value then it throws an error:
"The calling thread cannot access this object because a different thread owns it".
4. Here I understand that this error is coming because thread id has been changed. but unable to sort out this error.
Sample code as following
My backgroundworker class
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.ComponentModel;
using LoadingControl;
using System.Windows.Forms;
namespace LoadingClass
{
public class BackgroundLoading
{
public delegate void RunFunction();
public BackgroundWorker Bw;
public RunFunction thisFunction;
LoadingWindow newLoading;
public BackgroundLoading(RunFunction newFunction)
{
try
{
thisFunction = newFunction;
Bw = new BackgroundWorker();
Bw.DoWork += new DoWorkEventHandler(Bw_DoWork);
Bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Bw_RunWorkerCompleted);
}
catch (Exception ex)
{
throw;
}
}
public void Start()
{
try
{
Bw.RunWorkerAsync();
newLoading = new LoadingWindow();
newLoading.ShowDialog();
}
catch (Exception ex)
{
throw;
}
}
void Bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
try
{
newLoading.Close();
}
catch (Exception ex)
{
throw;
}
}
void Bw_DoWork(object sender, DoWorkEventArgs e)
{
try
{
if (thisFunction != null)
{
thisFunction();
}
}
catch (Exception ex)
{
throw;
}
}
}
}
code on my wpf form is something like this
public void btnSave_Click(object sender, RoutedEventArgs e)
{
try
{
if (Validator.IsValid(this))
{
BackgroundLoading BL = new BackgroundLoading(SavePatient);
BL.Start();
}
}
catch (Exception ex)
{
Common.WriteToErrorLog(ex.Message, "btnSave_Click");
}
}
public void SavePatient()
{
txtAge.Text = txtAge.Text;
}
Please suggest if you have any solution...
Thanks in advance