What's the ecquievelant of the following in C#
Public Event MyEvent(arg1 as string, arg2 as int) Public Sub RaiseMyEvent() RaiseEvent MyEvent("bla bla",15) End Sub |
Public Event MyEvent(arg1 as string, arg2 as int) Public Sub RaiseMyEvent() RaiseEvent MyEvent("bla bla",15) End Sub |
event declaration
Seth Maffey
It sounds like you want to race the event outside of the class you've declared it. This is not possible. You can only add or remove events (+=/-=) from the outside (public domain). The event can only be raised from within the class where you've declared the event (private domain).
enid1229
But how would the temporary variable of the sample above guarantees thread-safety If the one and only user unsubscribes after if the result would be the same!
DotFrammie
I also made the changes to the RaiseMyEvent method (protected virtual, and called "On<event name>") because that's the convention.
Update: Of course the string and int should be wrapped in a custom EventArgs class and the signature of the delegate should be something like (object sender, MyEventArgs e)
Deepak_SQL
...not sure about vb! Can you give me an example of a possible thread-unsafe scenario
nougat
if (someEvent != null)
{
someEvent(foo);
}
doesn't - the value of someEvent can change between the check and the invocation.
However, using a temporary variable on its own doesn't guarantee that you'll see the most recent value of the delegate list.
See this part of my threading article for my preferred way of dealing with events, including making the event subscription/unsubscription threadsafe.
MJC_Eagle
Right - you need the delegate.
delegate void MyEventEventHandler(string arg1, int arg2);The actual translation is:
public
public event MyEventEventHandler MyEvent;
public void RaiseMyEvent()
{
if (MyEvent != null)
MyEvent("bla bla",15);
}
(Note that you do not need a temporary variable as one post showed)
David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB.NET to C# Converter
Instant VB: C# to VB.NET Converter
Instant J#: VB.NET to J# Converter
Clear VB: Cleans up outdated VB.NET code
UtterMan
nunuk
I focused on the literal translation - i.e., the C# equivalent to the original possibly un-thread-safe VB code. Is the original VB code thread-safe - or does VB make this thread-safe behind the scenes
Alex Chertov
Marius T.
Steve Wertz
public delegate void MyEventHandler(string arg1, int arg2);
public event MyEventHandler MyEvent;
protected virtual void OnMyEvent(string arg1, int arg2)
{
MyEventHandler temp = MyEvent;
if (temp != null)
{
temp(arg1, arg2);
}
}