Asynchronous event handling

I have Windows Form class which creates another class (server) and subscribes to it's events. Some of these events are raised from worker threads. I don't like the fact that events are handled synchronously, this can cause deadlock. I would prefer to handle some of these events asynchronously, with minimal changes in existing code.
I think about two ways:
1) Instead of raising events from server, invoke form method asynchronously using BeginInvoke. But in this case server must have knowledge about client, and this is really bad.
2) Client can decide whether to handle event asynchronously. In some event handlers client invokes another method using BeginInvoke, and immidiately returns. Something like this:

void OnAsynchronousEvent(int n1, int n2)
{
     this.BeginInvoke(new MyDelegate(this.ActualEventHandler), new object[]{n1, n2});
}

void ActualEventHandler(int n1, int n2)
{
    // do something here while worker thread continues
}

The second way looks good for me, but I am afraid that I am missing some language feature which allows to do this better. Is there better way?
LVL 48
AlexFMAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

enwhyseeCommented:
You've got the general idea down, although is OnAsynchronousEvent a handler for something else? Here's a short code sample to show the simplest usage of this concept:

public delegate void DelegateSomeEvent(int n1, int n2);

public class Foo : System.Windows.Forms.Form
{
      public void OnSomeEvent(int n1, int n2)
      {
          // update some UI control etc.
      }

      private void btnDoStuff_Click(object sender, System.EventArgs e)
      {
             Thread foo = new Thread(new ThreadStart(ThreadFunction));
             foo.Start();
      }

      private void ThreadFunction()
      {
             BeginInvoke(new DelegateSomeEvent(this.OnSomeEvent), new object[] { 1, 2 } );
      }
}
AlexFMAuthor Commented:
This is exactly what I don't want to do. Server (ThreadFunction) must know name of client's handler function (OnSomeEvent). In my case server and client are different classes, and server doesn't know anything about client. Events allow to do this.
devsolnsCommented:
Another possible way to improve performance is to invoke the event delegate asynchronously from within the class defining the event.

protected void TriggerEvent()
{
      (OnEvent != null)
      {
            IAsyncResult ar = OnEvent.BeginInvoke(null, null, null, null);
            // usual way - > OnEvent(null, null);
                                //do some work here
                                OnEvent.EndInvoke(ar)
      }
}                  

public event EventHandler OnEvent = null;

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

devsolnsCommented:
If your concerned with having to wait and call EndInvoke (which you should definatly do) you can implement a fire and forget wrapper that will handle cleanup (calling endinvoke) automatically for you.
AlexFMAuthor Commented:
This looks like what I need, but I cannot compile this. Event is raised from C++/CLI code:

OnParametersChangedAS(n1, n2);

When I replace it with:

OnParametersChangedAS->BeginInvoke(exposure, gain, nullptr, nullptr);

I get C3918 error. Can you give me working example in C#, I can translate it to C++. In your sample, what is the class to which BeginInvoke belongs?
AlexFMAuthor Commented:
Actually, your code is working. It is my problem now to translate it to C++.
devsolnsCommented:
cool, let me know if you need anything further.  take care.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.