Click here to Skip to main content
15,907,183 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Heloo,

I have an application and i want to use a "Please wait...loading" window.
I have an example, its work, but i cant execute my code because is not in the same thread.

An example,

In a winForm1 in the load event i have:

C#
string NumeClientCautat = txtCautaDupaNume.Text;
this.sClienti.DataSource = SetariAmanet.TotiClienti(NumeClientCautat);
InformatiiDespreClientContracte();


To use "Please wait..." i have to rewrite the code to something like that:

C#
winProgresIncarcare.AsyncProcessDelegate method = delegate
			{
string NumeClientCautat = txtCautaDupaNume.Text;
this.sClienti.DataSource = SetariAmanet.TotiClienti(NumeClientCautat);
InformatiiDespreClientContracte();
			};
			base.StartWait(method);


He gives me an error:

the control is not in the same thread....
C#
this.sClienti.DataSource = SetariAmanet.TotiClienti(NumeClientCautat);
InformatiiDespreClientContracte();
Posted

You can only access controls from the thread that created them - the UI thread.
In order to do anything with them from a different thread, you have to use Invoke. The code I use is:
C#
private void AddNewTab(string tabName)
    {
    if (InvokeRequired)
        {
        Invoke(new MethodInvoker(delegate { AddNewTab(tabName); }));
        }
    else
        {
        TabPage tp = new TabPage(tabName);
        myTabControl.TabPages.Add(tp);
        }
    }
private void ShowProgress(int percent)
    {
    if (InvokeRequired)
        {
        Invoke(new MethodInvoker(delegate { ShowProgress(percent); }));
        }
    else
        {
        myProgressBar.Value = percent;
        }
    }
If instead of an aysnc delegate you used a BackgroundWorker, there's no need for you to do the invoking.
The BackgroundWorker offers status reporting across thead borders on its own.
1. Set the BackgroundWorker.WorkerReportsProgress property to true.
2. Within the worker routine call ((BackgroundWorker)sender).ReportProgress().
3. Do the UI changes (including progress bar) within BackgroundWorker.ProgressChanged event handler.
 
Share this answer
 
Hi
Controls have Invoke method which you can call it like this:

C#
label1.Invoke(new Action(() =>
{
    // do here gui work
}));


Inside you can do work that requires the GUI thread like updating a label or so.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900