|
Good Day,
I am using the Bgworker component in C# to do some CPU Intensive and time consuming work.
This work, to be exact, is to make a matrix (2D Array) out of a byte array.
So that's, byte[] 1D -> byte[,] 2D
So I'm using a for loop to do the convertion, so every step in the loop, I call the MatrixFormation_ProgressChanged to update the progress bar.
Now I ran the application but the problem is, eventhough I'm using BGWorker, when I try to do something with the form (Click on something, Minimize, Maximize, Move the Window) the form will just freeze (But the thread is running). After the process, the form will be back with the message "Matrix Completed!", the results are okay.
I also noticed that if I removed the ProgressChanged event to trigger the progress bar to update, freezing won't occur.
So how can I make the form NOT TO FREEZE during the work process without removing the ProgressChanged event?
PS: Matrix Formation isn't the only job I'm working so suggesting to change the process of the matrix formation won't help me.
Thank you in advance.
|
|
|
|
|
Hi,
sounds like you do have some illegal cross-thread access to some control.
did you by any chance:
- create or modify the progress bar in some thread other than the main or "GUI thread"?
as in the BackgroundWorker's RunWorkerAsync (e.g. make it visible?)
- access some other Control (say read a TextBox.Text) from inside RunWorkerAsync?
Normally these illegal actions should result in an InvalidOperationException, unless
you've set some Control.CheckForIllegalCrossThreadCalls false (which is a very bad idea).
If none of the above applies, I suggest you show actual code.
Luc Pattyn [Forum Guidelines] [My Articles]
this months 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
|
|
|
|
|
The Progress bar and the Label that represents the percentage of the progress bar is created during design time. (Using the Designer).
Here's the code:
private void MatrixFormation_DoWork(object sender, DoWorkEventArgs e)
{
ByteStream = File.ReadAllBytes(LoadFile.FileName);
int Rows = ByteStream.Length / PasswordLength;
int Remainder = ByteStream.Length % PasswordLength;
double Percentage = 0;
ByteMatrix = new byte[Rows,PasswordLength];
int I = 0;
for (int R = 0; R < Rows; R++)
{
if (MatrixFormation.CancellationPending)
{
e.Cancel = true;
return;
}
for (int C = 0; C < PasswordLength; C++)
{
ByteMatrix[R, C] = ByteStream[I++];
}
Percentage=(double)I / (double)ByteStream.Length * 100.00;
MatrixFormation.ReportProgress(Convert.ToInt32(Percentage),String.Format("{0:f}",Percentage));
}
if (Remainder != 0)
{
RemainderPile = new byte[Remainder];
for (int R = 0; R < Remainder; R++)
{
RemainderPile[R] = ByteStream[I++];
MatrixFormation.ReportProgress(Convert.ToInt32(Percentage), String.Format("{0:f}", Percentage));
}
}
}
private void MatrixFormation_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pbar.Value = e.ProgressPercentage;
lblPercentage.Text = e.UserState.ToString();
pbar.Refresh();
lblPercentage.Refresh();
}
private void MatrixFormation_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
lblS1.BackColor = Color.Red;
MessageBox.Show("Job has been cancelled!", "Cancellation Successful", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
lblS1.BackColor = Color.DodgerBlue;
lblS1.Refresh();
}
Note that ByteMatrix, PasswordLength and ByteStream are global variables.
Thank you!
|
|
|
|
|
Hi,
I suspect LoadFile; it'd better not be a Control (such as an OpenFileDialog)...
Luc Pattyn [Forum Guidelines] [My Articles]
this months 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 saw a post on here a while back that showed how to manipulate a bunch of buttons (button1, button2, button3, etc. ) with a for loop. Can anyone tell me how to do this with, say, 10 buttons? Thanks in advance.
- I love D-flat!
|
|
|
|
|
foreach(Control control in Controls)
{
Button btn = control as Button;
if (btn != null)
{
btn.BackColor = Colors.Red;
}
}
This will make all the buttons on a form red. The btn.BackColor line is a guess, the rest is golden.
Christian Graus - Microsoft MVP - C++
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|
|
OK. Is there another way? The one I swa had like button(for blah..), or something like that. But thanks.
- "Achieving all knowledge does not mean achieving all wisdom." some wise dude
- I love D-flat!
|
|
|
|
|
hi.. is that a good idea to use the expression blend for my C# design.. ?
i would like to know if i had created a project completely in visual c# .. can i use expression blend to change the design of that project?
or i need to start a project completely from expression blend first?
|
|
|
|
|
angels777 wrote: can i use expression blend to change the design of that project?
I don't see why not.
"Any sort of work in VB6 is bound to provide several WTF moments." - Christian Graus
|
|
|
|
|
take simple example... if let say i create a button with functionality in visual c#... so i use Blend to open that project..
how do i change the button design which created in Visual c# in Blend? my previous idea was to delete that button and use blend's button to replace... but if like this the functionality will be lost if i delete the button..
my friend said i must create the design in Blend.. not in visual c#
|
|
|
|
|
If you want to use Blend to create a project, then unless it's already a WPF project, I think you need to use Expression to start with.
Christian Graus - Microsoft MVP - C++
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|
|
Hello all,
How do we read the .txt file and extract the data to DataGrid according to specific rows and columns? For example if the .txt file has a Table of Contents that has subcategories in it, how should I extract the Table of Contents as rows in the DataGrid and the subcategories as by columns? Do we have that similar kind of tutorial here?
I would be great if somebody here could write a similar running program for tutorial.
Thanks.
|
|
|
|
|
It depends on how the data is structured/separated within the .txt file. Post a short example of the file's content.
A better solution is xml if you have control over the file type.
|
|
|
|
|
For example if I have these in my file.txt
Table of Contents:
1. Main Page
2. Preface
3. Chapter 1: Basic
- Hello World
- Windows forms
- Controls
- Application Settings
4. Chapter 2: Dialogs
- Standard Dialogs
- Styles
5. Chapter 3: Controls
- Standard Controls
- Custom Controls
and then display them on a DataGrid like this
Chapter No. Table of Contents Categories Page No.
Main Page 5
Preface 6
1 Basic Hello World 7
Windows Forms 8
Controls 9
App Settings 10
2 Dialog Standard Dialogs 11
Styles 12
3 Controls Standard Controls 13
Custom Controls 14
Could somebody please give an example how this is done in C#?
-- modified at 7:34 Saturday 24th November, 2007
|
|
|
|
|
you can use OLEDB text reader to connect to the text file and get its contents in a datatable and set that datable as datasource for the datagrid.
something like:
<br />
<br />
Dim str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\textfilepath\;Extended Properties='text;HDR=Yes;FMT=Delimited'" ' HDR=No if textfile deos not have header row<br />
<br />
Dim conn As OleDbConnection<br />
Dim da As OleDbDataAdapter<br />
conn = New OleDbConnection(str)<br />
<br />
strSql = "select * from textfilename.txt" ' or .csv<br />
da = New OleDbDataAdapter(strSql, conn)<br />
dtable = New DataTable("kkinvoices")<br />
da.Fill(dtable)<br />
datagrid.datasource=dt<br />
datagrid.databind()<br />
check this[^] for complete connection string...
-----
|
|
|
|
|
Woah, thats not C#, thats VB.
My current favourite word is: PIE!
Good ol' pie, it's been a while.
|
|
|
|
|
I know that.. because I had the code in VB. so I just posted.. its not difficult at all to convert it to C#;P
-----
|
|
|
|
|
Fair enough
My current favourite word is: PIE!
Good ol' pie, it's been a while.
|
|
|
|
|
I all. I have a strange case with display timer
my code look like this:
Timer myTimer = new Timer();
public static int nr = 1;
private void button1_Click(object sender, EventArgs e)
{
myTimer.Interval = 1000;
myTimer.Enabled = true;
myTimer.Start();
myTimer.Tick += new EventHandler(myTimer_Tick);
}
void myTimer_Tick(object sender, EventArgs e)
{
string a = "";
int tid1 = 0;
int tid2 = 0;
a = label21.Text;
tid1 = Convert.ToInt32(a);
tid2 = (int)tid1 - nr;
label21.Text = tid2.ToString();
}
But if i click on a stop button with:(myTimer.Stop()), then when i press on play button again the string (nr) has change to 2 and next time 3
How do i make this work??
Anyone with a good idea??
Tnx!!!
|
|
|
|
|
Almost no textbook or college course teaches you to use a debugger.
But you should.
Try selecting the first line in myTimer_Tick(), hit F9 to set a breakpoint, then run the program. When it stops there, put your mouse over the variables or look at the Watch box to see what the values are on the variables. Then execute one line at a time (Debug -> Step Over) and figure out what's wrong.
It's a really good way to fix problems and learn programming.
By the way, what exactly are you trying to do?
|
|
|
|
|
First of all : Avoid declaring many variables. So
Instead of
void myTimer_Tick(object sender, EventArgs e)<br />
{<br />
string a = "";<br />
int tid1 = 0;<br />
int tid2 = 0;<br />
a = label21.Text;<br />
tid1 = Convert.ToInt32(a);<br />
tid2 = (int)tid1 - nr;<br />
label21.Text = tid2.ToString();<br />
}
You can just use which is more readable.
void myTimer_Tick(object sender, EventArgs e)<br />
{<br />
label21.Text = (Convert.ToInt32(label21.Text) - nr).ToString();<br />
}
We can understand that you are decrementing a number and displaying it in a textBox.
Your question is "string (nr) has change to 2 and next time 3".
- nr is not a string, nr is a static int So what do you mean by this?
Do you mean the text is being incremented instead of decrementing. Well this is impossible as you see that there is no addition code in myTimer_Tick().
Best Regards.
|
|
|
|
|
Hey All,
I am trying to run a C# GUI Form on Fedora 8 using mono. If I run console applications, everything runs fine, but if I try to run a simple GUI application, I get the following exception (by the way, I didn't have to install mono, since it came with Fedora 8, but my guess is I am missing a graphic component needed to run GUI forms):
<br />
mono HelloWorldGUICS.exe<br />
<br />
Unhandled Exception: System.TypeInitializationException: An exception was thrown by the type initializer for System.Windows.Forms.Form ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeInitializationException: An exception was thrown by the type initializer for System.Drawing.GDIPlus ---> System.DllNotFoundException: gdiplus.dll<br />
at (wrapper managed-to-native) System.Drawing.GDIPlus:GdiplusStartup (ulong&,System.Drawing.GdiplusStartupInput&,System.Drawing.GdiplusStartupOutput&)<br />
at System.Drawing.GDIPlus..cctor () [0x00000] --- End of inner exception stack trace ---<br />
<br />
at <0x00000> <unknown method><br />
at System.Drawing.Image.InitFromStream (System.IO.Stream stream) [0x00000] <br />
at System.Drawing.Image..ctor (System.Runtime.Serialization.SerializationInfo info, StreamingContext context) [0x00000] <br />
at System.Drawing.Bitmap..ctor (System.Runtime.Serialization.SerializationInfo info, StreamingContext context) [0x00000] <br />
at <0x00000> <unknown method><br />
at (wrapper managed-to-native) System.Reflection.MonoCMethod:InternalInvoke (object,object[])<br />
at System.Reflection.MonoCMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] --- End of inner exception stack trace ---<br />
<br />
at System.Reflection.MonoCMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] <br />
at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] <br />
at System.Runtime.Serialization.ObjectRecord.LoadData (System.Runtime.Serialization.ObjectManager manager, ISurrogateSelector selector, StreamingContext context) [0x00000] <br />
at System.Runtime.Serialization.ObjectManager.DoFixups () [0x00000] <br />
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadNextObject (System.IO.BinaryReader reader) [0x00000] <br />
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObjectGraph (System.IO.BinaryReader reader, Boolean readHeaders, System.Object& result, System.Runtime.Remoting.Messaging.Header[]& headers) [0x00000] <br />
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.NoCheckDeserialize (System.IO.Stream serializationStream, System.Runtime.Remoting.Messaging.HeaderHandler handler) [0x00000] <br />
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize (System.IO.Stream serializationStream) [0x00000] <br />
at System.Resources.ResourceReader.ReadNonPredefinedValue (System.Type exp_type) [0x00000] <br />
at System.Resources.ResourceReader.ReadValueVer1 (System.Type type) [0x00000] <br />
at System.Resources.ResourceReader.ResourceValue (Int32 index) [0x00000] <br />
at System.Resources.ResourceReader+ResourceEnumerator.get_Value () [0x00000] <br />
at System.Resources.ResourceSet.ReadResources () [0x00000] <br />
at System.Resources.ResourceSet.GetObject (System.String name, Boolean ignoreCase) [0x00000] <br />
at System.Resources.ResourceManager.GetObject (System.String name, System.Globalization.CultureInfo culture) [0x00000] <br />
at System.Resources.ResourceManager.GetObject (System.String name) [0x00000] <br />
at System.Windows.Forms.Locale.GetResource (System.String name) [0x00000] <br />
at System.Windows.Forms.Form..cctor () [0x00000] --- End of inner exception stack trace ---<br />
<br />
at <0x00000> <unknown method><br />
at HelloWorldGUICS.Form1..ctor () [0x00000] <br />
at (wrapper remoting-invoke-with-check) HelloWorldGUICS.Form1:.ctor ()<br />
at HelloWorldGUICS.Form1.Main () [0x00000] <br />
Pete Soheil
DigiOz Multimedia
http://www.digioz.com
|
|
|
|
|
DigiOz Multimedia wrote: System.DllNotFoundException: gdiplus.dll
As far as I can see, you're missing a DLL called gdiplus.dll.
Kristian Sixhoej
"Failure is not an option" - Gene Kranz
|
|
|
|
|
If you are missing the GDI+ dll, that would explain why the error only happens with GUI apps. GDI+ is the whole drawing library thing that c# uses.
My current favourite word is: PIE!
Good ol' pie, it's been a while.
|
|
|
|
|
The Undefeated wrote: If you are missing the GDI+ dll, that would explain why the error only happens with GUI apps. GDI+ is the whole drawing library thing that c# uses.
Found this article which seemed to explain at least one of the errors above:
http://www.mono-project.com/DllNotFoundException[^]
It didn't fix my problem though, because even though there was a GDI+ library at "/usr/lib", it was called "libgdiplus.so.0" and "libgdiplus.so.0.0.0" (wrong folder and wrong name).
I tried to reinstall the GDI+ library, but the machine froze and I had to reboot to get it back.
Pete Soheil
DigiOz Multimedia
http://www.digioz.com
|
|
|
|