473,734 Members | 2,211 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Control.Invoke. ..Lots of controls and need help starting...

Ok,
I start my thread job:

Thread t = new Thread(new
ThreadStart(inv oicePrintingLon gRunningCodeThr ead));
t.IsBackground = true;
t.Start();

There are lots of calls to controls and many happen in function calls
from invoicePrinting LongRunningCode Thread. I need just an example in
getting started with my thread job with Invoking so that this will
always run and not fizzle out by not doing it right.
Here is the thread job (it's not that long):

private void invoicePrinting LongRunningCode Thread ()
{
Hide();

//listBox1.Items. Add("Network : " + SystemInformati on.Network );

if (button7.Text == "&Start Printing Invoices")
{
//temp name test
button7.Text = "&Invoices Are Being Processed";
///Run in separate thread

// ThreadStart myThreadDelegat e = new
ThreadStart(Thr eadFunction1.ge tOneAtATime);
// Thread thr1 = new Thread(myThread Delegate);
// thr1.Start();
bool couNTer1 = false;
do
{
// Form1 findThread = new Form1();
label15.Text = ("0" + " Invoices Left to Print");
loadInvoiceCont ainer();
label15.Text = (Convert.ToStri ng(Class1.cI) + " Invoices Left to
Print");
button7.Text = "&Watching for New Invoices";
if(Class1.cI > 0)
{
gotoForeach();
}
} while (couNTer1 == false);
}
else
{
// button7.Text = "&Start Printing Invoices";
PrinterBreaks = "BreaksOn";
// Thread tid1 = new Thread(new
ThreadStart(fin dThread.getOneA tATime ) );
// tid1.Abort();
}
}

Any help is appreciated.
Thanks,
Trint

Nov 17 '05 #1
19 6733
As you are running on a non-UI thread you have to push any UI requests back
to the main UI thread. The InvokeRequired property on a Control specifies
whether an invoke is required or not. It really depends on the underlying
implementation of a Control whether or not it must be invoked but the general
"safe" rule is that you must interact with a control only on the main UI
thread. Some controls may handle this automatically in which case your code
would work just fine. For others the following skeleton implementation is
what you want:

delegate void StringDelegate ( Control target, string parm );
void SetText ( Control target, string text )
{
if (target.InvokeR equired)
target.Invoke(n ew StringDelegate( SetText), new object[] { target, text
});
else
target.Text = text;
}

The code basically determines if it is running on the UI thread. If it
isn't then in invokes the same method on the UI thread (Control.Invoke ). If
it is on the UI thread then it simply sets the property. By changing the
delegate, Invoke arguments and the else-block you can modify this to work
with any property or method. Note that this is a blocking call. Use
BeginInvoke/EndInvoke to make it async.

Most controls don't implement this automatically for performance reasons but
I wouldn't be surprised if they don't migrate that way. For library code
that you write to encapsulate this stuff you should probably do this
automatically for your callers. For example instead of exposing a progress
bar on the status bar of your main form you should instead expose a method
from your main form to interact with the progress bar. In this case the
above logic should be encapsulated in the method you write.

As an aside I would also recommend that you minimize your cross-thread calls
and UI interaction. I'd recommend building an object that contains the
required UI changes and then invoke a method to update the UI with the object
contents when the thread is done (unless this is progress information). This
is especially true of list-style controls like ListBox and ListView. It
depends on how you want your UI to react though.

Hope this helps,
Michael Taylor - 9/16/05

"trint" wrote:
Ok,
I start my thread job:

Thread t = new Thread(new
ThreadStart(inv oicePrintingLon gRunningCodeThr ead));
t.IsBackground = true;
t.Start();

There are lots of calls to controls and many happen in function calls
from invoicePrinting LongRunningCode Thread. I need just an example in
getting started with my thread job with Invoking so that this will
always run and not fizzle out by not doing it right.
Here is the thread job (it's not that long):

private void invoicePrinting LongRunningCode Thread ()
{
Hide();

//listBox1.Items. Add("Network : " + SystemInformati on.Network );

if (button7.Text == "&Start Printing Invoices")
{
//temp name test
button7.Text = "&Invoices Are Being Processed";
///Run in separate thread

// ThreadStart myThreadDelegat e = new
ThreadStart(Thr eadFunction1.ge tOneAtATime);
// Thread thr1 = new Thread(myThread Delegate);
// thr1.Start();
bool couNTer1 = false;
do
{
// Form1 findThread = new Form1();
label15.Text = ("0" + " Invoices Left to Print");
loadInvoiceCont ainer();
label15.Text = (Convert.ToStri ng(Class1.cI) + " Invoices Left to
Print");
button7.Text = "&Watching for New Invoices";
if(Class1.cI > 0)
{
gotoForeach();
}
} while (couNTer1 == false);
}
else
{
// button7.Text = "&Start Printing Invoices";
PrinterBreaks = "BreaksOn";
// Thread tid1 = new Thread(new
ThreadStart(fin dThread.getOneA tATime ) );
// tid1.Abort();
}
}

Any help is appreciated.
Thanks,
Trint

Nov 17 '05 #2
> There are lots of calls to controls and many happen in function calls
from invoicePrinting LongRunningCode Thread. I need just an example in
getting started with my thread job with Invoking so that this will
always run and not fizzle out by not doing it right.
Here is the thread job (it's not that long):


Again, I'd suggest looking at the sample code I linked to before:
http://www.pobox.com/~skeet/csharp/t...winforms.shtml

That gives an example of updating two labels, which is the kind of
thing you're
doing here. Basically, look through your code and identify everything
which
updates the UI - and make sure that runs in a thread-safe manner as per
the article.

Jon

Nov 17 '05 #3
Michael,
When it reaches gotoForeach();, from there a statusbar is constantly
updated and so are several label controls. I will have to somehow
address each call to a control correctly throughout the code.
From the snipit I have given, it doesn't show the calls to update the

status bar or the text labels. Here is an another example of where I
need help in protecting this code:
public void PrinterStatusNP I7FC6D2()
{

string trayvalue = string.Empty;
///Tray 3
RFC1157.Mgmt mib = new RFC1157.Mgmt();
Snmp.ManagerSes sion sess=new
Snmp.ManagerSes sion(Class1.sel ectLJPrinter,"p ublic");
Snmp.ManagerIte m mi=new
Snmp.ManagerIte m(sess,mib.OID( "1.3.6.1.2.1.25 .3.5.1.1.1"));
// listBox1.Items. Add("Tray 3".ToString( ));
// listBox1.Items. Add(mi.Value.To String());
trayvalue = Convert.ToStrin g(mi.Value);
label7.Text = string.Format(" Printer Status: {0}",trayvalue) ;
if (trayvalue == "0")
{
PrinterBreaks = "BreaksOn";
Tray3 frmText3 = new Tray3();
frmText3.ShowDi alog();
}

}

one more:

statusBarPanel2 .Reset();
statusBarPanel2 .Step();
statusBarPanel2 .ProgressPositi on = ((long)(Class1. toNerlOng));

Really would appreciate your help.
Thanks,
Trint

Nov 17 '05 #4
Jon,

I am working with your example at this very moment.
How would I be able to use Control.Invoke with updating the status bar
here:

statusBarPanel2 .Reset();
statusBarPanel2 .Step();
statusBarPanel2 .ProgressPositi on = ((long)(Class1. toNerlOng));

Thanks,
Trint

Nov 17 '05 #5
The correct way to deal with multiple threads and call back to main UI thread
in Winforms application is to use delegates to marshal data to UI threads.
It's also not recommended that "spawning threads from threads".

Take a look at the MSDN sample(Multithr eaded Windows Forms Control Sample)
at follwoing URL
http://msdn.microsoft.com/library/de...rmsControl.asp
Nov 17 '05 #6
Pass the "long" value to a method which does the reset, step and
progress position setting all within the same Control.Invoke call.

Jon

Nov 17 '05 #7
In your case I'd recommend creating a method on your form that accepts a
custom object (structure) that contains the label values and the progress bar
values. I'd then invoke this method in the secondary thread. This optimizes
your performance by making only a single cross-thread call per loop instead
of 3. Here is some sample code:

struct UpdateData
{
public UpdateData ( string status, long progress, params string[] items )
{
Status = status;
Progress = progress;
Items = items;
}
public string Status;
public string[] Items;
public long Progress;
}

class MyForm : Form
{
delegate void UpdateStatusDel egate ( UpdateData data );
void UpdateStatus ( UpdateData data )
{
if (InvokeRequired )
Invoke(new UpdateStatusDel egate(UpdateSta tus), new object[] { data
});
else
{
foreach(string item in data.Items)
listbox1.Items. Add(item);

label7.Text = data.Status;

statusBarPanel2 .Reset();
statusBarPanel2 .Step();
statusBarPanel2 .ProgressPositi on = data.Progress;
};
}
}

public void PrinterStatusNP I7FC6D2()
{
string trayvalue = string.Empty;
///Tray 3
RFC1157.Mgmt mib = new RFC1157.Mgmt();
Snmp.ManagerSes sion sess=new
Snmp.ManagerSes sion(Class1.sel ectLJPrinter,"p ublic");
Snmp.ManagerIte m mi=new
Snmp.ManagerIte m(sess,mib.OID( "1.3.6.1.2.1.25 .3.5.1.1.1"));

UpdateData data = new UpdateData();
string trayvalue = mi.Value.ToStri ng();
data.Items = new string[] { "Tray 3", trayvalue };
data.Status = String.Concat(" Printer Status: ", trayvalue);
f (trayvalue == "0")
{
//This could be bad
PrinterBreaks = "BreaksOn";
Tray3 frmText3 = new Tray3();
frmText3.ShowDi alog();
}

//Maybe this is separate??
data.Progress = (long)Class1.to NerlOng;

//UI update
frmObj.UpdateSt atus(data);
}

One thing that I'd be concerned about is that form creation in your
secondary thread. That is generally a bad idea because you are creating a
new form on a background thread. I'd try to do that some other way instead.

Michael Taylor - 9/16/05

"trint" wrote:
Michael,
When it reaches gotoForeach();, from there a statusbar is constantly
updated and so are several label controls. I will have to somehow
address each call to a control correctly throughout the code.
From the snipit I have given, it doesn't show the calls to update the

status bar or the text labels. Here is an another example of where I
need help in protecting this code:
public void PrinterStatusNP I7FC6D2()
{

string trayvalue = string.Empty;
///Tray 3
RFC1157.Mgmt mib = new RFC1157.Mgmt();
Snmp.ManagerSes sion sess=new
Snmp.ManagerSes sion(Class1.sel ectLJPrinter,"p ublic");
Snmp.ManagerIte m mi=new
Snmp.ManagerIte m(sess,mib.OID( "1.3.6.1.2.1.25 .3.5.1.1.1"));
// listBox1.Items. Add("Tray 3".ToString( ));
// listBox1.Items. Add(mi.Value.To String());
trayvalue = Convert.ToStrin g(mi.Value);
label7.Text = string.Format(" Printer Status: {0}",trayvalue) ;
if (trayvalue == "0")
{
PrinterBreaks = "BreaksOn";
Tray3 frmText3 = new Tray3();
frmText3.ShowDi alog();
}

}

one more:

statusBarPanel2 .Reset();
statusBarPanel2 .Step();
statusBarPanel2 .ProgressPositi on = ((long)(Class1. toNerlOng));

Really would appreciate your help.
Thanks,
Trint

Nov 17 '05 #8
Michael,
I don't know if this matters, but the frmText3.ShowDi alog(); form is
like a message box (in the way it works) that just says "Tray 3 is out
of paper" and one button "Problem solved" that exits
frmText3.ShowDi alog();.
If I had time at this point, I would certainly rather find some other
way of informing the user other than using controls.
Thanks,
Trint

Nov 17 '05 #9
MessageBox-style dialogs are "OK" and won't cause a crash normally however
you are somewhat limiting yourself. If you were to move away from
Thread.Start and instead go with the ThreadPool (with all its advantages)
then the dialog would cause a problem and potentially crash the app because
the ThreadPool threads are limited and your thread will block until the user
reacts. If your thread was started multiple times you could drain the
ThreadPool. Of course this may be just what you want. One thing that I have
done in the past in these cases is add a status box to my UI where I send
messages like this. It is better than a status panel because the information
isn't lost the next time I update the status. Instead the user sees that
there was a problem. Again it is a matter of requirements. So for now you
should be alright but you might want to look at an alternative in the future.

Michael Taylor - 9/16/05

"trint" wrote:
Michael,
I don't know if this matters, but the frmText3.ShowDi alog(); form is
like a message box (in the way it works) that just says "Tray 3 is out
of paper" and one button "Problem solved" that exits
frmText3.ShowDi alog();.
If I had time at this point, I would certainly rather find some other
way of informing the user other than using controls.
Thanks,
Trint

Nov 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1587
by: Ingo Schasiepen | last post by:
Hi there, i'm evaluating if c# is suited to replace a script language. Most of the elements of this language can be replaced with a c#-library, but it also has some realtime-like elements. E.g., in this language, the following code is possible: { Int32 i=0; OnEvent ( ... ) {
5
2108
by: Martin Maat [EBL] | last post by:
Hi, I have a GUI application that responds to events coming from an externaql application. In the implementing code for the event I need to create a GUI control and "parent" the control into the GUI. Doing this directly fails, it is not allowed to parent a control that was not created on the main GUI thread into the main GUI through another thread (an exception is thrown on "control.Parent = container;"). So I have to create the...
2
3007
by: rawCoder | last post by:
Hi I am having this InvalidOperationException with message Cannot call Invoke or InvokeAsync on a control until the window handle has been created This is raised when i try to invoke a method with arguments I need to do this as the method is being called Asynchronously from elsewhere using delegate's BeginInvoke method. The form is well created/initialized yet the messages states otherwise.
5
3592
by: serge calderara | last post by:
Dear all, I am new in asp.net and prepare myself for exam I still have dificulties to understand the difference between server control and HTML control. Okey things whcih are clear are the fact that for server control component , code is running on the server side. But if I take as example a Label. I place on a webform an HTM label control and a WebForm label control, I could see that properties are different for
11
1899
by: BoloBaby | last post by:
OK, check this out... I have a form with a panel control and button on it (outside the panel control). I have two event handlers - one handles the click event of the button on the form. The other handles a custom "CardInserted" event for a class I wrote that watches for smart cards to be inserted into an attached smart card reader.
31
7237
by: jcrouse | last post by:
Is there a quick and easy way to change the color of a label controls border from the default black to white? Thank you, John
14
14652
by: Rolf Welskes | last post by:
Hello, I have an ObjectDataSource which has as business-object a simple array of strings. No problem. I have an own (custom) control to which I give the DataSourceId and in the custom-control so I get the ObjectDataSource. No problem ..... ObjectDataSource src = .... //is ok i have it
1
1865
by: Alec MacLean | last post by:
Hi, Outline of problem: I've built a set of user controls that are used to output questions for a survey and gather the responses using simple radio buttons. I'm adding an optional textbox to the question control to allow individual typed responses per question. I've got a maximum length to enforce which matches the underlying data table design.
0
8776
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9310
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9182
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6031
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2724
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.