|
To avoid this problem, I would suggest you use a BackgroundWorker. This component will handle much of the threading for you and allow you a way modify controls on the form. It has a few very helpful methods...RunWorkerAsync() , ReportProgress(), and WorkDone().
You can call the ReportProgress method within your for loop like
<br />
private void StartProcess()<br />
{<br />
this.bgWorker.RunWorkerAsync();<br />
}<br />
<br />
private void bgWorker_DoWork()<br />
{<br />
AddCNums();<br />
}<br />
<br />
private void AddCNums()<br />
{<br />
for(int i = 0; i < 20, i++)<br />
{<br />
this.bgWorker.ReportProgress(0, i)}<br />
}<br />
<br />
}<br />
<br />
private void bgWorker_ReportProgress(object sender, ProgressChangedEventArgs e)<br />
{<br />
if(e.ProgressPercentage == 0)<br />
{<br />
int i = (int)e.UserState;<br />
this.cText.Text += ("Main thread: {0}\n", i);<br />
<br />
}<br />
}<br />
<br />
<br />
It's very clean.
Lester
http://www.lestersconyers.com
|
|
|
|
|
You'll have to add a Method to handle it that looks something like this...
private delegate void TextBoxUpdater(TextBox t, String s);
private void UpdateTextBox(TextBox t, String s){
if(t.InvokeRequired) {
t.Invoke(new TextBoxUpdater(UpdateTextBox), Object[]{t, s}));
} else {
t.Text = s;
}
}
Call this from your thread routine in place of manually setting the control text.
The above code may not work, I didn't compile it, but you get the idea. You have to check "InvokeRequired" on a control that you want to cross thread, and call the updating method on the UI thread using a delegate.
Scott
"Run for your life from any man who tells you that money is evil. That sentence is the leper's bell of an approaching looter." --Ayn Rand
|
|
|
|
|
|
Thank you very much half-life.
But is it really safe to do?? I mean what you suggested did work 100% but I read on Internet that this is used for Debugging, just to avoid error messages!
I think someone should write article about Multi-threading on CP. I searched but didn't find any.
- Stop thinking in terms of limitations and start thinking in terms of possibilities -
modified on Monday, April 7, 2008 2:52 PM
|
|
|
|
|
Nothing is Stupid When u do not know it
The Property is MS Idea so it's probebly doable
The right way goes like this:
<br />
public delegate void RefToFunction(string s);<br />
<br />
<br />
RefToFunction handle = new RefToFunction(UpdateTextBox);<br />
<br />
<br />
string s = "Test";<br />
object[] param = { s };<br />
<br />
<br />
this.Invoke(handle, param);<br />
<br />
<br />
public static void UpdateTextBox(string s)<br />
{<br />
MessageBox.Show(s);<br />
}ode><br />
<br />
i did a lot of research about this so i hope i helped<br />
if u need any clarification just reply :):) <br />
<br />
<div class="ForumSig">Have Fun<br />
Never forget it</div>
|
|
|
|
|
don't set CheckForIllegalCrossThreadCalls false, this is a terrible hack, that WILL
result in malfunction, sooner or later (sooner if you are lucky).
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
Bingo, Thanks Luk this is what i intented
Have Fun
Never forget it
|
|
|
|
|
Hello,
I've built a DLL using an ASCII C compiler (NI-CVI). A certain function is to return a string.
Here is the code in C:
int get_description ( char sDescription[] )<br />
{<br />
strcpy (sDescription, "aaa");<br />
return 0;<br />
}
here is the code in C#:
[DllImport("C:\\funcs.dll")]
public static extern int get_description ( out string sDescription);
the exeption I get:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I have also tried substituting the string for char[], byte[] nothing works.
Please help me. Anyone?
yariv
|
|
|
|
|
long_il wrote: Please help me. Anyone?
They hide that information in the documentation[^]
led mike
|
|
|
|
|
Hi,
you should create a StringBuilder, give it sufficient "capacity", and pass the StringBuilder
object AND and int holding its capacity to the native code; the native code should
then fill the buffer, without overflowing its capacity. Hence use strncpy, not strcpy.
When returned to C#, you can call ToString() on the StringBuilder to get a real String.
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
i've enconterd the same problem with reading from ini files
and did as u said,
i actually even created the same princple with atrncpy
but still the problem occured, strange
Have Fun
Never forget it
|
|
|
|
|
Hi,
a string (=a read-only object) or a StringBuilder (=a writeable string with limited length)
can be passed easily from C# to native code; the marshalling is automatic.
other objects, such as all kinds of arrays, cannot passed as such; you need to help the
system, e.g. by using GCHandle and pinning the object, so it can't move while the native
code is dealing with it.
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
Got u
THANK a LOT
Have Fun
Never forget it
|
|
|
|
|
Many C# class contains Disposal method.
As long as it contains the method, I must call the method after using the class. Am I correct?
But I always find example codes like this:
Pen pen=new Pen(...);
// Using the object
// Never call the pen.Disposal
Confused...
I'm sorry for my poor English.
|
|
|
|
|
Well, you don't have to call it after you finish with the object. That is if you don't mind unmanaged resources being left unfreed. In most cases, the Dispose method is there for your application to tell the underlying code to dispose of unmanaged resources - there are exceptions where people are doing odd behaviour in the Dispose (such as closing a database connection - odd yes, but I have seen it), but it is good practice to Dispose of resources when you've finished with them.
In your example, you can do
using (Pen pen = new Pen)
{
} and the Dispose method is automatically called for you because the using (){} essentially converts into a try/finally block where the finally calls the Dispose method.
|
|
|
|
|
Always call Dispose transitively - in your Dispose override, call Dispose (or Close) on any resources that your class was holding on to. Yes, finalization is there as a backstop - but it's such a bad one, you never want your code to end up in the finalizer.
Database connections are a special case. Because the provider is normally pooling connections for you, it's more acquire/release than create/destroy. Best Practice is to acquire a connection just before executing an operation and release it just after. Don't go over the top, if you have a set of causally-related database activities you can execute them all on the same connection, but generally you should be using a using block with any connection you create.
DoEvents: Generating unexpected recursion since 1991
|
|
|
|
|
Now I'm very clear. Thanks all.
|
|
|
|
|
Hello
I have an excel file which contain some titles and dateand....
and a row that look like this:
Name Director Signature
how can i fill automatically this columns using c#.
Note: the row number to start with is 7.
best regards
dghdfghdfghdfghdgh
|
|
|
|
|
Hi,
Kindly note, the problem is that, following commands works perfect only 5 to 10 times in loop
and after then shows error when cursor goes on
"Bitmap mybitmap = new Bitmap(pictureBox2.Image);" after 5 to 10 times in loop.
Error is : !NullReferenceExeption was unhandled
Object reference not set to an instance of an object
-----------------------------------------------
i am using:
-----------------------------------------------
class gp
{
bitmap gp1
{
GetDC(PlatformUSER32.GetDesktopWindow());
CreateCompatibleDC(hdc);
ShowWindow(hdc, 3);
size_.cx = PlatformUSER32.GetSystemMetrics(SM_CXSCREEN);
size_.cy = PlatformUSER32.GetSystemMetrics(SM_CYSCREEN);
CreateCompatibleBitmap(hdc, size_.cx, size_.cy);
}
}
----------------------------------------------
picturebox1.image = gp.gp1()
Bitmap mybitmap = new Bitmap(pictureBox1.Image); <<-- this works perfect 5 to 10 time in loop
after 5 to 10 times it is showing said error.
Kindly help me to solve this problem.
Thank you
(Riaz)
|
|
|
|
|
Windows has a very small pool of device contexts available for programs to do drawing. You're exhausting the pool by not returning the objects once you've finished with them. Call DeleteDC to clean up the compatible DC you created (which you're currently not capturing - this is the return value of CreateCompatibleDC), and ReleaseDC to release the handle you get back from GetDC. Do not mix these calls up - the OS will not like it if you delete one of the pooled DCs.
If you're going to be do any unmanaged drawing I recommend you read 'Programming Windows, Fifth Edition' by Charles Petzold.
DoEvents: Generating unexpected recursion since 1991
|
|
|
|
|
Hi,
1.
from MSDN on GetDC:
a) "After painting with a common DC, the ReleaseDC function must be called to release the DC.
Class and private DCs do not have to be released. ReleaseDC must be called from the same
thread that called GetDC. The number of DCs is limited only by available memory."
b) If the function succeeds, the return value is a handle to the DC for the specified window's client area.
You don;t use the return value???
2.
from MSDN on CreateCompatibleDC:
a) "When you no longer need the memory DC, call the DeleteDC function."
b) If the function succeeds, the return value is the handle to a memory DC.
You don't use the return value???
3.
please show actual code; what you have shown would not compile.
4.
Please use PRE tags to show multi-line code snippets.
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
ok Sir,
I am replying with compelete code
|
|
|
|
|
|
OK,
that is looking much better already. it's a pitty you still are not using PRE tags though.
Some remarks:
1.
your while loop has no built-in delay, so it will run as hard as it can. Is that what you
intend? I would suggest you insert a Thread.Sleep(100); or so to slow it down
a bit, leaving some CPU cycles to other tasks.
2.
your while loop continuously replaces the image inside the PictureBox. You don't dispose
of the previous image. Doing so would improve system behavior.
3.
CreateCompatibleBitmap() may return zero; you are aware of that, since you test for it.
But when it does, so does your GetDesktopImage() method, resulting in the NullReference
that you are experiencing.
4.
CreateCompatibleBitmap() returns zero when something fails; MSDN tells you to call
GetLastError() to find out what went wrong, so that's what you should do.
BTW: Don't use P/Invoke to call the native GetLastError(), instead add SetLastError=true
to your DllImport line, and call Marshal.GetLastWin32Error() straight from C#.
If any of this is unclear, look it up in the documentation; make Google your friend.
5.
You may want to repeat remark 4 for other Win32 methods as well.
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
Thank you very much for your kind consideration
now I will try your said suggestions.
|
|
|
|