In my other methods I could do something like this,
public void Add(T item)
{
if (dispatcher.CheckAccess())
{
...
}
else
{
dispatcher.Invoke(new Action<T>(Add), item);
}
}
But how do I invoke a property for a situation like this?
public T this[int index]
{
get
{
...
}
set
{
if (dispatcher.CheckAccess())
{
...
}
else
{
dispatcher.Invoke(???, value, index); // <-- problem is here
}
}
}
Edit: The following paragraph no longer applies, as the OP's question has since been edited.
First off, your second code seems logically incorrect: You apparently want to call the setter, but while you provide a value for index
, you don't provide the actual value
(i.e. item
). I'll return to that issue in a second.
You could wrap an anonymous delegate or lambda function around the property setter, e.g. (using an anonymous delegate) to make it invokable:
dispatcher.Invoke(
new Action<T>( delegate (T item) { this[index] = item; } ),
item );
or (using a lambda function available since C# language version 3):
dispatcher.Invoke(
new Action<T>( (T item) => { this[index] = item; } ),
item );
Note: You create an anonymous delegate or lambda function that accepts one argument (item
). The other required argument (index
) is taken from the "outer" context. (The term closure comes to mind.) I see this as the only way how you would not have to change your dispatcher
to a delegate type that is sometimes invoked with two arguments instead of one.
If this however is not an issue, the Invoke
code could change to e.g.:
dispatcher.Invoke(
new Action<int,T>( (int index, T item) => { this[index] = item; } ),
index, item );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With