delegate handling, or incorrect syntax... either way how can i do this?

E

Eric Newton

Given the following code,

Public class ProgressFormManager
Public Sub BeginInvoke(ByVal method As [Delegate], ByVal args() As Object)
Dim asyncCallback As New System.Threading.WaitCallback(method)
System.Threading.ThreadPool.QueueUserWorkItem(asyncCallback, args)
End Sub
.... [other implementation details]
End Class

[in the Form codebehind]
Private Sub Button1_Click(...
Dim pfm as new ProgressFormManager(Me) 'Me is the form to become the
owner
pfm.BeginInvoke(addressof LongMethodCallback, new object() { arg1, arg2,
arg3 })
End Sub

Private Sub LongMethodCallback(byval param as object)
Dim args() as object = DirectCast(param, object())
'do lengthy work
End Sub

since ProgressFormManager attempts to keep the form created on the same
thread as the caller and then fork a worker thread, I'm using the
QueueUserWorkItem

problem follows:
A) Vb compiler fails on in ProgressFormManager.BeginInvoke with two errors:
1) 'System.Threading.WaitCallback' is a delegate type. Delegate construction
permits only a single AddressOf expression as an argument list. Often an
AddressOf expression can be used instead of a delegate construction.
2) 'AddressOf' expression cannot be converted to 'System.Delegate' because
'System.Delegate' is not a delegate type.

any ideas?

I know in C# this wouldnt even be a problem.
 
D

David

Given the following code,

Public class ProgressFormManager
Public Sub BeginInvoke(ByVal method As [Delegate], ByVal args() As Object)
Dim asyncCallback As New System.Threading.WaitCallback(method)
System.Threading.ThreadPool.QueueUserWorkItem(asyncCallback, args)
End Sub
... [other implementation details]
End Class

You have to declare method as an actual delegate type. You may as
well use the WaitCallback type, since that's what you want anyway.

Public Sub BeginInvoke(ByVal method as Threading.WaitCallback)
ThreadPool.QueueUserWorkitem(method, args)
End Sub

And back in the form, it's simply

pfm.BeginInvoke(addressof LongMethodCallback)

(I'm not showing the args argument to avoid linebreaks, but obviously
just add that back in).
I know in C# this wouldnt even be a problem.

Actually, you can't pass System.Delegates around like this in c# either.
In c#, you'd need to explicitly instantiate the delegate when you called
BeginInvoke. VB.Net will do that for you, but you have to let it know
what kind of delegate to create. You can either do that in the function
declaration, as above, or explicitly create the delegate when you call
the function.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top