0

how to make a method wait for an event? when the function is called, it will wait for an event to occur to continue execution. is that possible?

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by serkan sendur
1

That is the default behavior. Here is a test class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace daniweb
{
  public delegate void OnSerkanEvent(object sender, SerkanEventArgs e);

  public class Serkan
  {
    public event OnSerkanEvent OnEvent;
    public Serkan()
    {
    }
    public void DoWork()
    {
      if (this.OnEvent != null)
      {
        SerkanEventArgs args = new SerkanEventArgs();
        Console.WriteLine(string.Format("Firing event(s): {0:G}", DateTime.Now));
        this.OnEvent(this, args);
        Console.WriteLine(string.Format("Events fired: {0:G}", DateTime.Now));
      }
    }
  }
  public class SerkanEventArgs : EventArgs
  {
    private bool _handled;

    public bool Handled
    {
      get { return _handled; }
      set { _handled = value; }
    }
    public SerkanEventArgs()
    {
    }
  }
}

Then calling it:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace daniweb
{
  public partial class frmSerkan : Form
  {
    private Serkan serkan;

    public frmSerkan()
    {
      InitializeComponent();
      serkan = new Serkan();
      serkan.OnEvent += new Serkan.OnSerkanEvent(serkan_OnEvent);
      serkan.OnEvent += new Serkan.OnSerkanEvent(serkan_OnEvent2);
    }

    void serkan_OnEvent(object sender, SerkanEventArgs e)
    {
      System.Threading.Thread.Sleep(1000);
      Console.WriteLine(string.Format("Event 1: {0:G}", DateTime.Now));
    }

    void serkan_OnEvent2(object sender, SerkanEventArgs e)
    {
      System.Threading.Thread.Sleep(1000);
      Console.WriteLine(string.Format("Event 2: {0:G}", DateTime.Now));
    }

    private void button1_Click(object sender, EventArgs e)
    {
      serkan.DoWork();
    }
  }
}

Results in:

Firing event(s): 8/18/2009 4:33:57 AM
Event 1: 8/18/2009 4:33:58 AM
Event 2: 8/18/2009 4:33:59 AM
Events fired: 8/18/2009 4:33:59 AM

I tested it another way too and I see the same output:

private void button2_Click(object sender, EventArgs e)
    {
      Serkan s = new Serkan();
      Delegate d = Delegate.Combine(new OnSerkanEvent(serkan_OnEvent), new OnSerkanEvent(serkan_OnEvent2));
      s.OnEvent += (OnSerkanEvent)d;
      s.DoWork();
    }
Votes + Comments
Nice post! And very instructive.
0

i just woke up, i will look at it when i am available, then for sure will have something to say.

Thanks

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.