Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't Invoke via Delegate built into .NET

I understand that .NET is multi-threaded and that is a good thing, but I continually run into issues when I have a background worker for example that is updating some control on my form and I have to do:

Private Sub SetRowCellBoolValueThreadSafe(ByVal row As Integer, ByVal col As Integer, ByVal value As Boolean)
    If dgvDatabase.InvokeRequired Then
        Dim d As New SetRowCellBoolValueCallback(AddressOf SetRowCellBoolValue)
        Me.Invoke(d, New Object() {row, col, value})
    Else
        SetRowCellBoolValue(row, col, value)
    End If
End Sub

Delegate Sub SetRowCellBoolValueCallback(ByVal row As Integer, ByVal col As Integer, ByVal value As Boolean)

Private Sub SetRowCellBoolValue(ByVal row As Integer, ByVal col As Integer, ByVal value As Boolean)
    dgvDatabase.Rows(row).Cells(col).Value = value
End Sub

My question is why is this not built into the framework - surely if I am trying to update a DataGridView it should be intelligent enough to know when the update is from another thread and it could do all the above itself?

like image 753
Matt Wilko Avatar asked Sep 01 '11 08:09

Matt Wilko


People also ask

What is invoke delegate C#?

19.6 Delegate invocation C# provides special syntax for invoking a delegate. When a non- null delegate instance whose invocation list contains one entry, is invoked, it invokes the one method with the same arguments it was given, and returns the same value as the referred to method.

Why use delegates instead of methods in c#?

Delegates allow methods to be passed as parameters. Delegates can be used to define callback methods. Delegates can be chained together; for example, multiple methods can be called on a single event. Methods don't have to match the delegate type exactly.

Is delegate a reference type in c#?

A delegate is a reference type that can be used to encapsulate a named or an anonymous method.

Is delegate is a reference type?

Delegates are reference types.


1 Answers

The would mean turning every operation on a UI control into a delegate, just in case it needed to be marshalled to a different thread. That would be hugely expensive. Additionally, it presupposes that you always want to do the same thing - use Invoke rather than BeginInvoke for example.

I agree it's a bit of a pain in the neck to have to do this manually, but the next versions of C# and VB should make life a lot easier with async methods.

(As an aside, I don't think you really want to use ByRef for all those parameters... is it possible that you're not really clear what ByRef means?)

like image 67
Jon Skeet Avatar answered Oct 09 '22 11:10

Jon Skeet