I have wcf servise that Update db it is takes 10-15 sec,and i wont to run/show my form with loading/waitting statusbar while servise working, and when service is finished i need to close the watting form.
My problem is when i run ShowDialog(); it is get stuck on it , and don't go to my service.
What i doing wrong here?
My code
My function
public static void UpdateSNXRATES(object sender, EventArgs e)
{
WaitForm waitF = new WaitForm();
waitF.ShowDialog();//here it stuck
using (var Server = new ServiceReference.Service1Client())
{
Server.ClientCredentials.Windows.ClientCredential.Domain = strDomain;
Server.ClientCredentials.Windows.ClientCredential.UserName = strUser;
Server.ClientCredentials.Windows.ClientCredential.Password = strPassword;
success=Server.UpdateSNXRATES();
}
waitF.Close();
}
My WaitForm code
public partial class WaitForm : Form
{
public WaitForm()
{
InitializeComponent();
}
private void WaitForm_Load(object sender, EventArgs e)
{
radWaitingBar1.StartWaiting();
radWaitingBar1.WaitingSpeed = 100;
radWaitingBar1.WaitingStep = 5;
}
}
ShowDialog() is a blocking call, i.e. the current thread will keep waiting on this line until the form is closed (by the user). You should show your WaitForm on a different thread than the main application thread, combined with Invoke() call to ensure that you don't do illegal cross-thread operations. You can use BackgroundWorker component to load and show your WaitForm on a different thread.
Alternately and preferably, you should move your service initialization and running code to the BackgroundWorker. That will ensure you don't need any Invokes.
Example
ServiceReference.Service1Client Server;
WaitForm waitF;
public static void UpdateSNXRATES(object sender, EventArgs e)
{
BackgroundWorker bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.DoWork += bw_DoWork;
bw.RunWorkerCompleted += bw_RunWorkerCompleted;
bw.RunWorkerAsync();
waitF = new WaitForm();
waitF.ShowDialog();
}
static void bw_DoWork(object sender, DoWorkEventArgs e)
{
Server = new ServiceReference.Service1Client();
Server.ClientCredentials.Windows.ClientCredential.Domain = strDomain;
Server.ClientCredentials.Windows.ClientCredential.UserName = strUser;
Server.ClientCredentials.Windows.ClientCredential.Password = strPassword;
success = Server.UpdateSNXRATES();
}
static void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
waitF.Close()
}
Related
I'm making(trying) to make a dialogue box similar to the openFileDialogue where the program flow of the Main Thread is stalled until the OPF.ShowDialogue() function stalls while running a separate thread.
I have a OpenFileDialogue_Gui class which uses a semaphore and a background worker.
The background worker is first launched to generate a separate form with the necessary user-interface
Then the semaphore stalls the main thread until the user clicks one of the buttons on the background thread's form.
Then it releases the semaphore and the result is sent back to the calling function.
Sounds nice in theory, but there's a problem. The background-worker is not displaying its form and it's not working.
Here's the code :
public class openfiledialogue_Gui
{
Semaphore semStall = new Semaphore(0, 1);
BackgroundWorker bck = new BackgroundWorker();
public openfiledialogue_Gui()
{
bck.WorkerSupportsCancellation = true;
bck.DoWork += Bck_DoWork;
bck.RunWorkerCompleted += Bck_RunWorkerCompleted;
}
public enum enuResult { Ok, Cancel, _num };
public enuResult ShowDialogue()
{
bck.RunWorkerAsync();
semStall.WaitOne();
return eResult;
}
enuResult eResult = enuResult.Cancel;
void EventOk_click(object sender, EventArgs e)
{
eResult = enuResult.Ok;
strFilename = "ok clicked";
semStall.Release();
}
void EventCancel_click(object sender, EventArgs e)
{
eResult = enuResult.Cancel;
strFilename = "cancel clicked";
semStall.Release();
}
private void Bck_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e){semStall.Release();}
private void Bck_DoWork(object sender, DoWorkEventArgs e)
{
Form frmShow = new Form();
Button btnOk = new Button();
btnOk.Text = "ok";
Button btnCancel = new Button();
btnCancel.Text = "Cancel";
btnOk.AutoSize
= btnCancel.AutoSize
= true;
frmShow.Controls.Add(btnOk);
frmShow.Controls.Add(btnCancel);
frmShow.ControlBox = false;
btnOk.Location = new Point(100, 25);
btnCancel.Location = new Point(100, 75);
btnCancel.Click += EventCancel_click;
btnOk.Click += EventOk_click;
frmShow.Show();
}
public string strFilename = "this is a test";
public string Filename
{
get { return strFilename; }
}
}
Is there any way to make this work?
Sounds like you want to make a 'Modal Form'.
var form = new MyModalForm();
form.ShowDialog();
This will 'stall' the UI until you cancel (or otherwise close) the form.
I have a button in my WinForms application with the following Click event:
private void Button_Click(object sender, EventArgs e)
{
treasureFound = false;
refreshNumber = 0;
Label_StartDateTime.Text = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss");
while (!treasureFound)
{
Label_StatusData.Text = "Refreshed " + refreshNumber + " times.";
refreshNumber++;
using (WebClient client = new WebClient())
{
string htmlCode = client.DownloadString(webUrl);
if (htmlCode.Contains("Treasure"))
{
treasureFound = true;
Label_StatusData.Text = "Found.";
// etc etc
}
}
}
}
When the button is clicked, the UI thread locks up (not responding, labels don't update) until the while loop ends.
What can I do to keep the UI responsive? There should only be one WebClient instance at any one time.
you should execute the time-consuming tasks in a separate thread, so it will not block the main thread (aka your UI thread). One way is to use the BackgroundWorker.
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.WorkerReportsProgress = true;
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
Taken from: How to use a BackgroundWorker?
I have created a splash screen for a WinForm app. Everything works well until the splash screen is just a form with a background image and a label which has a static text - "Loading..."
I want to update the label continuously (with small delay in between) with texts - "Loading","Loading.","Loading.." and "Loading...". For this I have put the following code in my SplashScreen form:
private void SplashScreen_Load(object sender, EventArgs e)
{
lblLoading.Refresh();
lblLoading.Text = "Loading.";
Thread.Sleep(500);
lblLoading.Refresh();
lblLoading.Text = "Loading..";
Thread.Sleep(500);
lblLoading.Refresh();
lblLoading.Text = "Loading...";
Thread.Sleep(500);
}
Now the Splash Screen doesn't appear until the label in it gets updated to "Loading..."
Please help to let me know what I am doing wrong.
Code in my HomeScreen:
public HomeScreen()
{
//....
this.Load += new EventHandler(HandleFormLoad);
this.splashScreen = new SplashScreen();
}
private void HandleFormLoad(object sender, EventArgs e)
{
this.Hide();
Thread thread = new Thread(new ThreadStart(this.ShowSplashScreen));
thread.Start();
//...Performing tasks to be done while splash screen is displayed
done = true;
this.Show();
}
private void ShowSplashScreen()
{
splashScreen.Show();
while (!done)
{
Application.DoEvents();
}
splashScreen.Close();
this.splashScreen.Dispose();
}
EDIT:
As suggested by some users here I have put the startup tasks in background thread and now I am displaying the Splash Screen from the main thread. But still the same issue persist. Here is the updated code of HomeScreen form:
public HomeScreen()
{
//...
this.Load += new EventHandler(HandleFormLoad);
}
private void HandleFormLoad(object sender, EventArgs e)
{
this.Hide();
SplashScreen sc = new SplashScreen();
sc.Show();
Thread thread = new Thread(new ThreadStart(PerformStartupTasks));
thread.Start();
while (!done)
{
Application.DoEvents();
}
sc.Close();
sc.Dispose();
this.Show();
}
private void PerformStartupTasks()
{
//..perform tasks
done = true;
}
and here's the Splash Screen :
private void SplashScreen_Load(object sender, EventArgs e)
{
lblLoading.Update();
lblLoading.Text = "Loading.";
Thread.Sleep(500);
lblLoading.Update();
lblLoading.Text = "Loading..";
Thread.Sleep(500);
lblLoading.Update();
lblLoading.Text = "Loading...";
Thread.Sleep(500);
}
You want a BackgroundWorker that posts ProgressChanged event, which will update the splash screen. The progress changed object could be a string, for example, that you'll display on your splash screen (back on the GUI thread).
You should handle the splash screen in the main thread, and the background work of initialising in the background thread (just as logixologist commented).
That said, the reason that your changed message doesn't show up is because the main thread is busy so it doesn't handle the events that redraws the control. Calling DoEvents in a background thread will only handle messages in that thread, and the messages to update the splash screen is in the main thread.
The Refresh method only invalidates the control, which would cause it to be redrawn if the main thread handled the event. You can use the Update method to force the redraw of the control:
private void SplashScreen_Load(object sender, EventArgs e)
{
lblLoading.Text = "Loading.";
lblLoading.Update();
Thread.Sleep(500);
lblLoading.Text = "Loading..";
lblLoading.Update();
Thread.Sleep(500);
lblLoading.Text = "Loading...";
lblLoading.Update();
}
But, this is only a workaround for the current code. You should really make the main thread handle the messages.
Thanks to all for answering my questions. Finally my issue is solved ! I changed my code such that start-up tasks are now being performed on a separate thread and splash screen is displayed from the Home Screen (main) thread. In the home screen I made use of Backgroundworker to update the 'Loading...' label.
I am posting my code here hoping it may also help someone in future..
For the Home Screen code plz see the EDIT part in my question. Here's the code of Splash Screen :
public SplashScreen()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = false;
lblLoading.Text = string.Empty;
}
private void SplashScreen_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (true)
{
for (int i = 1; i <= 20; i++)
{
System.Threading.Thread.Sleep(200);
worker.ReportProgress(i);
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
string dots = string.Empty;
for (int k = 1; k <= e.ProgressPercentage; k++)
{
dots = string.Format("{0}..",dots);
}
lblLoading.Text = ("Loading" + dots);
}
You have to define a background worker in your splash screen form.
Here is an example of what your splash screen could look like :
public partial class SplashScreenForm<T> : Form
{
private BackgroundWorker _backgroundWorker;
private Func<BackgroundWorker, T> _func;
private T _funcResult;
public T FuncResult { get { return _funcResult; } }
public SplashScreenForm(Func<BackgroundWorker, T> func)
{
this._func = func;
InitializeComponent();
this.label1.Text = "";
this._backgroundWorker = new BackgroundWorker();
this._backgroundWorker.WorkerReportsProgress = true;
this._backgroundWorker.DoWork += new DoWorkEventHandler(_backgroundWorker_DoWork);
this._backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(_backgroundWorker_ProgressChanged);
this._backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_backgroundWorker_RunWorkerCompleted);
_backgroundWorker.RunWorkerAsync();
}
private void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
if (worker != null)
{
_funcResult = this._func.Invoke(worker);
}
}
private void _backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState != null)
{
this.label1.Text = e.UserState.ToString();
}
}
private void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();
}
}
You can design it the way you want, maybe a pretty gif image, or whatever you can think of.
Call it this way :
private void HandleFormLoad(object sender, EventArgs e)
{
this.Hide();
var splash = new SplashScreenForm<bool>(PerformTask);
splash.ShowDialog(); // function PerformTask will be launch at this moment
this.Show();
}
private bool PerformTask(BackgroundWorker worker)
{
//...Performing tasks to be done while splash screen is displayed
worker.ReportProgress("loading..");
}
I created a wpf application.
In my application, i open a windows and i copy in background some files.
I would like to display and update a progressbar during thos copy.
I tried to use a BackgroundWorker :
public partial class FenetreProgressBar : Window
{
private readonly BackgroundWorker worker = new BackgroundWorker();
public FenetreProgressBar(ObservableCollection<Evenement.FichierJoint> CollectionFicJointsToAdd)
{
InitializeComponent();
worker.WorkerReportsProgress = true;
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.ProgressChanged +=worker_ProgressChanged;
worker.RunWorkerAsync(CollectionFicJointsToAdd);
}
private void ProgressChanged(double Persentage, ref bool Cancel)
{
if (Cancel)
this.Close();
worker.ReportProgress((int)Persentage);
}
private void Completedelegate()
{
this.Close();
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
ObservableCollection<Evenement.FichierJoint> collection = e.Argument as ObservableCollection<Evenement.FichierJoint>;
//2) On ajoute les fichiers joints à l'évènements ( ce qui va donc les copier dans le répertoire paramétré)
foreach (Evenement.FichierJoint FichierJoint in collection)
{
if (FichierJoint.strPathFichier.Length > 0)
{
Evenement.FichierJoint monFichierJoint = new Evenement.FichierJoint(FichierJoint.strPathFichier, App.obj_myEvenement.strEvtNumeroString);
MaProgressBar.Minimum = 0;
MaProgressBar.Maximum = 100;
monFichierJoint.copyObject.OnProgressChanged += ProgressChanged;
monFichierJoint.copyObject.OnComplete += Completedelegate;
monFichierJoint.AddFichierJoint();
}
}
}
private void worker_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
{
// Traitement terminé, on ferme la fenetre
this.Close();
}
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
MaProgressBar.Value = e.ProgressPercentage;
}
}
When the programme go here :
MaProgressBar.Minimum = 0;
MaProgressBar.Maximum = 100;
I have an exception : " The calling thread cannot access this object because a different thread owns it".
I have read severals answer on google and stackoverflow but i don't try to use this approach with the BackgroundWorker.
Anyone coule help me in order to avoid this exception and solve the problem please ?
Thanks a lot,
Best regards :)
You cannot modify UI objects from background worker. You need to invoke the methods on UI dispatcher like this -
App.Current.Dispatcher.Invoke((Action)delegate
{
MaProgressBar.Minimum = 0;
MaProgressBar.Maximum = 100;
});
But since you only need to set maximum an minimum values, i would suggest you to set these values outside of backgroundWorker in constructor -
public FenetreProgressBar(ObservableCollection<Evenement.FichierJoint>
CollectionFicJointsToAdd)
{
InitializeComponent();
MaProgressBar.Minimum = 0;
MaProgressBar.Maximum = 100;
worker.WorkerReportsProgress = true;
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.ProgressChanged +=worker_ProgressChanged;
worker.RunWorkerAsync(CollectionFicJointsToAdd);
}
Why don't you use C# new async and await new feature/keywords? they were specifically designed to make the UI responsive while doing lengthy operations.
You should try this:
_backgroundWorker.OnProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
and then
// Event handler
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Update main thread here
}
i have Windows Form in C# having Datagridview with large no. of records from database and some comboboxes,textbox and buttons.
so,i used another form having progressbar and backgroundworker so that data loading of mainform does not iritate enduser.
public partial class FirstForm : Form
{
MainForm mf;
public FirstForm()
{
InitializeComponent();
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
mf = new MainForm(); //inside constructor,code of data loading in gridview
mf.Update();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (p1.Value < p1.Maximum) //p1 name for progressbar
p1.Value++;
else
{
timer1.Enabled = false;
this.Hide();
mf.Show();
}
}
}
but when main form is displayed,it is blank and after 2/3 seconds datagridview and other controls appear.
how to solve this..?
or suggest other ideas to solve this problem.
Remove your code in Firstform and write mine in
programs.cs
static void Main()
{
Application.EnableVisualStyles();
Application.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
Application.SetCompatibleTextRenderingDefault(false);
System.ComponentModel.BackgroundWorker bw = new System.ComponentModel.BackgroundWorker();
bw.DoWork += new System.ComponentModel.DoWorkEventHandler(bw_DoWork);
bw.WorkerSupportsCancellation = true;
MainForm = new MainForm(); // creating main form
bw.RunWorkerAsync();
frm.Inittiate(); // Add this method to first form to loading and initiating
bw.CancelAsync(); // ending splashing
Application.Run(frm);
}
static void bw_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
AFirstForm splashForm = new FirstForm();
splashForm.TopMost = true;
splashForm.Show();
while (!(sender as System.ComponentModel.BackgroundWorker).CancellationPending)
{
splashForm.Refresh();
}
splashForm.Close();
e.Result = splashForm;
}