|
I wrote following code
Imports System.Threading
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim s As New ThreadStart(AddressOf progress)
Dim t As New Thread(s)
t.Start()
End Sub
Sub progress()
For x As Int32 = 1 To 10000
ProgressBar1.Value += 1
Next
End Sub
End Class
I want to increase progress bar value within separate thread. When i run this code it wasn't run as i suppose and it threw Invalid operation exception. It's message is "Cross-thread operation not valid: Control 'ProgressBar1' accessed from a thread other than the thread it was created on."
What happened here. Please someone explain it.
|
|
|
|
|
You cannot access form from another thread. To do this, you should write:
Invoke(New MethodInvoker(Sub() ProgressBar1.Value += 1))
Die Energie der Welt ist konstant. Die Entropie der Welt strebt einem Maximum zu.
|
|
|
|
|
Where should i place this code? please explain it with my example.
|
|
|
|
|
Instead of
ProgressBar1.Value += 1
just replace this line
Die Energie der Welt ist konstant. Die Entropie der Welt strebt einem Maximum zu.
|
|
|
|
|
|
Pasan,
Pasan148 wrote: I want to increase progress bar value within separate thread. When i run this code it wasn't run as i suppose and it threw Invalid operation exception. It's message is "Cross-thread operation not valid: Control 'ProgressBar1' accessed from a thread other than the thread it was created on."
You can achieve this very easily using the background worker class (http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx[^]).
Just enable progress change and supports cancellation on the background worker object. Then, in the Do_Work sub, report progress, and you can easily update your progressbar in the progresschanged event.
Hope this helps.
He who goes for revenge must first dig two graves.
|
|
|
|
|
I am trying to dissasemble a .net dll via reflector, one that has been in use in our company for ages, as practice. My future task will be to produce similar dll-a that are com interoparabile and activex compliant.
I am doing this in VB.net, and I have already been told that this is a big no-no, dlls of this sort are supposed to be made with C++ people say. I would guess that they are stating this because C++ uses pointers (which are heavily used in many DLLs when it comes to pointing to a pointer - i.e. memory location that holds particular relevant info).
Be as it may, I wish to proceed building this dll in vb.net to see how far I can get before I am forced to switch to C++ or C#...
I have already made a lot of fixes to the code, thus reducing the number of errors from over 120 to 30 which is, I would guess, a good start, but now I am facing several errors that are above my level of knowledge (I am a beginner after all) and I would like to get some information from people who are more experienced than me.
* First problem I encountered is the following: (this is an excerpt of code dealing with events that happen on a SERIAL port).
Public Custom Event OnCTS As OnCTS
AddHandler(ByVal value As OnCTS)
Me.OnCTS = DirectCast(Delegate.Combine(DirectCast(Me.OnCTS, Delegate), DirectCast(value, Delegate)), OnCTS)
End AddHandler
RemoveHandler(ByVal value As OnCTS)
Me.OnCTS = DirectCast(Delegate.Remove(DirectCast(Me.OnCTS, Delegate), DirectCast(value, Delegate)), OnCTS)
End RemoveHandler
End Event
This is what the reflector did for me, unfortunately the first "DELEGATE" keyword after DirectCast has an error attached to it: "expression expected". I have tried using "raiseevent" instead but if I use that, another piece of code later will not work.
Currently I have this:
Public Custom Event OnCTS As OnCTS
AddHandler(ByVal value As OnCTS)
End AddHandler
RaiseEvent()
End RaiseEvent
RemoveHandler()
End RemoveHandler
End Event
But I do not know the proper syntax for this nor where to begin. I have only recently started doing event driven code.
* A similar error (DELEGATE keyword, "keyword does not name a type") happens in this line of code:
Me.parent.Invoke(DirectCast(New EventHandler(AddressOf callback.ToMainThread), Delegate))
* The third problem is in this line of code
Dim key As New RegKey(&H80000002)
&H80000002 - error code "constant expression not representable as UINT, here is the enumeration for the above mentioned constant.
Public Enum VasKeys ' as uint32 Here I had to remark away the "as uint32"
' Fields
ClassesRoot = &H80000000
CurrentUser = &H80000001
LocalMachine = &H80000002
Users = &H80000003
End Enum
* The fourth problem happens in this example of code:
Dim bytes As Byte() = SerialParser.StringToByteArray(str)
flag2 = Win32Serijski.WriteFile(Me.m_handle, bytes, bytes.Length, (numBytesWritten), o)
Second line, 2nd parameter "bytes" states that: " Value of type '1-dimensional array of Byte' cannot be converted to 'Byte'. "
The pinvoke looks like this:
<DllImport("kernel32", EntryPoint:="WriteFile", SetLastError:=True)> _
Private Shared Function WriteFile(ByVal handle As IntPtr, ByRef bytes As Byte, ByVal numBytesToWrite As Integer, ByRef numBytesWritten As Integer, ByRef overlapped As OVERLAPPED) As Integer
End Function
* Next is the problem of casting (BR is BaudRate)
Private BR As Integer = &H2580
dcb.BaudRate = DirectCast(Me.BR, UInt32)
It says it cannot cast integer to UINT32
* The fifth problem is as follows
Win32Serijski.GetCommState(Me.m_handle, AddressOf dcb) where dcb is a structure, and addressof demands a method so it wont accept dcb
Here is my DCB structure
Public Structure DCB
Public DCBlength As UInt32
Public BaudRate As UInt32
Public Flags As UInt32
Public wReserved As UInt16
Public XonLim As UInt16
Public XoffLim As UInt16
Public ByteSize As Byte
Public Parity As Byte
Public StopBits As Byte
Public XonChar As Byte
Public XoffChar As Byte
Public ErrorChar As Byte
Public EofChar As Byte
Public EvtChar As Byte
Public wReserved1 As UInt16
End Structure
* Finally I am having problems with the callback wrapper
wrapper = New CallbackWrapper(Me) '{.DoOnCTS = True, .BoolData = Me.m_old_cts}
It will not accept the {} portion stating that Value of type 'Jebemtisvepospisku.Port' cannot be converted to 'Integer'.
This is my callback wrapper:
Friend Class CallbackWrapper
' Methods
Friend Sub New(ByVal parent As Jebemtisvepospisku.Port)
Me._parent = parent
End Sub
Friend Sub ChangeToMainThread(ByVal o As Object, ByVal ea As EventArgs)
Me._parent.DoEvent(Me)
End Sub
' Fields
Friend BoolData As Boolean = False
Friend DoOnCTS As Boolean = False
Friend DoOnDCD As Boolean = False
Friend DoOnDSR As Boolean = False
Friend DoOnForceClose As Boolean = False
Friend DoOnRead As Boolean = False
Friend DoOnRI As Boolean = False
Friend DoOnWritten As Boolean = False
Friend IntData As Integer = 0
Private _parent As Jebemtisvepospisku.Port = Nothing
Friend StringData As String = Nothing
End Class
I have no idea why the value of my .port class turns out to be anything, it should not have a value yet the callback wrapper (which I copy pasted from another example) requires an integer. I was trying to handle threading, and this SHOULD in theory be used to switch between main thread and other threads , depending on which event occurs.
I wish to thank you for your help (if any, lol) in advance!
|
|
|
|
|
Hi,
I will attempt and answer a couple of your issues in separate messages, so they can expand individually if required.
try this:
Public Enum VasKeys as uint32
ClassesRoot = &H80000000U
CurrentUser = &H80000001U
LocalMachine = &H80000002U
Users = &H80000003U
End Enum
there are a couple of suffixes that indicate a different type, U means unsigned.
it is documented here[^].
|
|
|
|
|
Now thats a good tip, I was aware of the various types but I did not know how to easily fix problems like the above.
|
|
|
|
|
Fixed, in this case "UL" was the correct suffix to "cast" the number to UINT32
|
|
|
|
|
that would be "UI" not "UL", in .NET "long" variables take 64 bit, you don't need that, do you?
|
|
|
|
|
|
the prototype should indicate either an array or a pointer, so try this:
<DllImport("kernel32", EntryPoint:="WriteFile", SetLastError:=True)> _
Private Shared Function WriteFile(ByVal handle As IntPtr, ByRef bytes As Byte(), ByVal numBytesToWrite As Integer, ByRef numBytesWritten As Integer, ByRef overlapped As OVERLAPPED) As Integer
End Function
I made bytes an array of bytes, not a single byte.
I expect that to work for you, I haven't done it in VB.NET yet, I normally do C# (and P/Invoke from C# to C).
|
|
|
|
|
That was my appraisal as well, I did "fix" the pinvoke method by adding the () making bytes an array BUT as I made that change I thought to myself "that probably wont work" and so I decided to ask for help.
I havent yet figured out the ins and outs of pinvoking so I am still overly cautious to change things. Love the wiki, hate the "trial and error" part of pinvoking
|
|
|
|
|
There is http://www.pinvoke.net[^], which is interesting, not always accurate, sometimes not complete. It does not offer a VB prototype for WriteFile!
I am (or should still be) working on this article[^]; what it says about passing arrays is correct, but there is a simpler way I haven't mentioned nor fully tested yet, and that is your way.
|
|
|
|
|
Ah I have read it some time ago when I first encuntered pinvoking problems, at the time it seemed a large wall of text so I skipped over most of it, only looking at the bits that interested me, now that I have more knowledge I will read it once again.
Thats the problem with really detailed articles, one should really read them more than once, and at different time, as one progresses in knowledge. Its like watching Star Wars as a kid and as an adult, different things. Things stops revolving around light sabres and Leia become interesting
|
|
|
|
|
you are mixing signed and unsigned integers. It isn't very important which you choose, however being consistent is what matters. So either make BR an unsigned integer (use the U suffix again!), or modify the structure to a signed baudrate. The P/Invoke stuff will not mind you doing so.
|
|
|
|
|
|
Hrizip wrote: Dim key As New RegKey(&H80000002)
I don't know what class RegKey is, nor what constructor(s) it has. If it needs an unsigned integer parameter, once again apply a U suffix or switch to a signed integer definition.
|
|
|
|
|
|
Hrizip wrote: wrapper = New CallbackWrapper(Me) '{.DoOnCTS = True, .BoolData = Me.m_old_cts}
So try a multi-line approach, along the lines wrapper.DoOnCTS = True
FYI: You may or may not prefer to apply a With construct.
|
|
|
|
|
Some overall comments:
1.
I have my doubt you will ever get this to work; it looks like a lot of code is present, none of which is yours, no source and no documentation available. Normally one starts from scratch, creates a little piece of code, gets it to work, then expand it a bit, etc. That way most if not all code is familiar and in working order all of the time. You will have a lot of code, some mistakes, and not much that works I expect.
2.
You can tell Reflector to show a method in a language of choice. If VB.NET is not your prime language, and maybe C# is, it may help to look at the C# code it suggests.
3.
I was told there are add-ins for Reflector that would turn an entire DLL into source code right away.
4.
There are programs, and web services, that translate code from one .NET language to another. I use them occasionally when trying to answer questions here on this forum.
5.
Make Google your friend. All of MSDN and heaps of useful articles will be at your disposal, simply by entering a few keywords.
|
|
|
|
|
I seem to be learning best the hard way, every time I try learning something the easy way I end up not knowing anything. This is why I love looking at other peoples code and learning their syntax. I have done a lot of work on my own serialport classes under VB.NET so most of this code is known to me. The unknown parts being delegating and event handling.
I havent found a good tutorial on using delegates under VB.net nor on event handling, but I have both present here in this code sample, now if I could (given enough time) reverse engineer this, I would end up understanding both on a relatively known problem (serial port communication).
VB.net is my language of choice, but I had done some minor work in C#, I have already compared C# and VB.net reflector outputs and this did help me solve SOME of the problems, just not all.
I would be interested in reflector addon that turns an entire dll into source code, I have been searching under addons for it, but I havent been able to find it, is it third party (not listed on reflectors home page)?
Yeah there some sort of a plugin for VS that handles PINVOKING, I also use it a lot.
Turns out that using google shake and bake solutions makes me patchwork code together without knowing WHY it works, unfortunately due to time constraints on my projects, I do the majority of things this way. AFAIK most programmers do. It makes me feel unsecure about my knowledge and the behaviour of the code that isnt all mine.
I love learning how the stuff actually works.
|
|
|
|
|
IMO the quickest way to learn a new technology is by reading a book about it. A tutorial is meant to take you from zero to first understanding; you will not be getting why things are done a particular way, and not another way, just by looking at existing code.
I can't help you with articles on delegates and events if you insist on them using VB examples.
|
|
|
|
|
Fixed a few things;
1) Delegate is a system.delegate method so there was a problem in namespaces, had to explicitly state what a "DELEGATE" is (a system.delegate in this case)
2) Unresolved at this time, mostly because I am clueless when it comes to delegates
This is the C# variant of one of the events/delegates:
public delegate void OnForceClose(int ErrorCode);
public event OnForceClose OnForceClose;
When expanded it reveals the following:
[MethodImpl(MethodImplOptions.Synchronized)]
public void add_OnForceClose(OnForceClose value)
{
this.OnForceClose = (OnForceClose) Delegate.Combine(this.OnForceClose, value);
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void remove_OnForceClose(OnForceClose value)
{
this.OnForceClose = (OnForceClose) Delegate.Remove(this.OnForceClose, value);
}
VB.net variant looks like this:
Public Custom Event OnForceClose As OnForceClose
MethodImpl(MethodImplOptions.Synchronized) _
Public Sub add_OnForceClose(ByVal value As OnForceClose)
Me.OnForceClose = DirectCast(Delegate.Combine(Me.OnForceClose, value), OnForceClose)
End Sub
MethodImpl(MethodImplOptions.Synchronized) _
Public Sub remove_OnForceClose(ByVal value As OnForceClose)
Me.OnForceClose = DirectCast(Delegate.Remove(Me.OnForceClose, value), OnForceClose)
End Sub
I have no idea what this does, I can make an educated guess and say that this delegate is "announced" by using an older routine that does not use "add handler", "remove handler" and "raiseevent" instead it plugs into an older system.delegate method and therefore uses a different way of adding and removing a handler (see c# example).
The VB example seems to show how to splice two delegates (or events) into one by the means of system.delegate.combine method, I have no idea why this is used in this example and what it should accomplish.
I would need to find out what the difference is between the above mentioned examples and the addhandler/removehandler/raiseevent (which I am partly familiar with) and then try to recreate the whole thing.
Any help/insight would be most welcome.
|
|
|
|
|