Monday, January 16, 2006

Delegates in vb.net part II

A delegate also has built in methods that allow background execution of the method it points to which is what we are going to use here. Most times I start a task on a background thread I use Thread.Start(). Unfortunately if you have a method that takes parameters you can not use Thread.Start. Instead we will use a delegate which will allow us to pass parameters to a method running on another thread.

I have a project where I need to write to a file on a background thread. The WriteFile method takes one parameter (the file path).

public sub WriteFile(byVal outputFile as String)
//implementation
end sub

To build a delegate I simply do this:

private Delegate Sub FileWriteDelegate(ByVal outputFile as String)

Note that the delegate has the same method signature as the method I am going to call.

private sub DoTask()
WriteFile("c:\temp.txt")
end sub

To run it on a background thread I change the DoTask method to create an instance of the delegate and then call BeginInvoke.

private sub DoTask()
Dim x As New FileWriteDelegate(AddressOf WriteFile)
x.BeginInvoke(outputFile, Nothing, Nothing)
end sub

You will note that when you call beginInvoke you must specify a string of filename. I have set the other params to nothing. I will cover the other two params of BeginInvoke in my next post. That is pretty much it! I will try to write more on Delegates as I think this is the one feature that most vb.net developers know nothing about or don't know how / when to use them.

0 Comments:

Post a Comment

<< Home