Tuesday, May 10, 2011

Multi-Threading and Delegates

There are 2 ways of using multi-threading in .NET.
1. By making use of delegates
2. By using Thread class

-- Multi Threading using Delegate
This is best approch for passing parameter and checking status of current execution.

E.g.
Delegate Function MyDelegate(ByVal text as String) as String

Function PrintStuff(ByVal text as String) as String
Console.WriteLine(text)
Thread.Sleep(5000)
Return "Success"
End Function

Sub Main()
Dim d as MyDelegate = AddressOf PrintStuff
d.BeginInvoke("hello world", Nothing, Nothing)
'I can do more stuff here
End Sub

Here we have a Main thread and a second thread to print some stuff. Also, a delegate with the same signature as the function we want to run (PrintStuff) already exists. Very simply, the Main thread creates a delegate that points to PrintsStuff and calls for the delegate to start executing PrintStuff on a separate thread. A parameter is passed to PrintStuff in the process and Main can continue working while PrintStuff is busy.

Now suppose you want to know when PrintStuff finishes because you want the result “Success”. We can do this by the use of a callback function.

First, we create the callback function

Sub MyCallback(ByVal result as IAsyncResult)
Console.WriteLine("Now I know PrintStuff finished")
End Sub

Then we make sure the callback function gets called by changing the previous BeginInvoke command to


d.BeginInvoke("hello world", New AsyncCallback(AddressOf MyCallback),Nothing)

1 comment:

  1. Caesars Casino reopens in CO at $5.3B price | DrmCD
    Caesars Casino 익산 출장안마 in 포항 출장샵 Las Vegas will reopen at 공주 출장마사지 $5.3 billion, with the opening of the Caesars Casino 파주 출장샵 hotel and adjacent 안성 출장마사지 hotel. The resort is part of the

    ReplyDelete