Delegate and Callback
Call Back With Delegate Explained
Public Class Form1
Private Sub
Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Dim RP As New RunningProcess
RP.SomeLongRunningProcess()
'With Above
Logic We can;t get Update from Loop inside.Means Proceess which is Inside will
not
able to update to 'Current Click Event
which File is been Processed or File is been Downloaded or
Email is been Sent. 'Which record of
Database is been Processed
'To Over come
this Issue DELEGATE can be used with CallBack feature of Delegate.
Dim X As Boolean =
RP.SomeLongRunningProcessWithCallBack(AddressOf GetCallBackDelegateValue)
End Sub
Public Sub
GetCallBackDelegateValue(Value As Integer)
'Console.Write(Value)
Me.ListBox1.Items.Add(Value)
End Sub
End Class
Public Class RunningProcess
Public Function SomeLongRunningProcess()
For intloop As Integer = 0 To 1000000
'Some Long
Running Process. File Downloading, Email Sending Creating Files,
'Complex Database Operartion
Dim i As Integer
i = intloop * 110 + 10
Next
Return True
End Function
Public Delegate Sub CallBackDelegate(Value As Integer)
Public Function SomeLongRunningProcessWithCallBack(Current As CallBackDelegate)
For intloop As Integer = 0 To 100
'Some Long
Running Process. File Downloading, Email Sending Creating Files, Complex
Database
'Operartion
Dim i As Integer
i = intloop * 110 + 10
Current(i)
Next
Return True
End Function
End Class
NOTE: If not delegate. You
will need to pass Control as parameter to function which will update Value of [i]
in Listbox. That will make you Class Dependent to Return Value in Listbox only.
If control has to be changed or DLL will have to be changed also if Logic is in
different Class/DLL Or if same data is to be represented in other form using GRID
or Textbox.
Logic with Listbox as
Parameter will not work. Above example make output control free and any change
in user interface will not effect the DLL or working.
Threading Call Back With Delegate
Explained
Private Delegate Sub AddValueToList(Value As Integer)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Dim Thrd As New Threading.Thread(AddressOf StartProcess)
Thrd.Start()
End Sub
Private Sub StartProcess()
Dim RP As New RunningProcess
Dim X As Boolean = RP.SomeLongRunningProcessWithCallBack(AddressOf
GetCallBackDelegateValue)
End Sub
Private Sub GetCallBackDelegateValue(Value As Integer)
ListBox1.Invoke(New AddValueToList(AddressOf AddValueToListBoxControl),
Value)
End Sub
Public Class RunningProcess
Public Delegate Sub CallBackDelegate(Value As Integer)
Public Function SomeLongRunningProcessWithCallBack(Current As
CallBackDelegate)
For intloop As Integer = 0 To 10000
'Some Long Running Process. File
Downloading, Email Sending Creating Files, Complex Database Operartion
Dim i As Integer
i = intloop * 110 + 10
Current(i)
Next
Return True
End Function
End Class
Comments
Post a Comment