I know this is really basic stuff but I’m struggling to wrap my mind around it.
Ok so I have a method that I want to run:
public static void DelegateTest(string testStuff)
{
for (int i = 0; i < 4; i++)
{
Console.WriteLine(testStuff);
}
}
Then, outside of the scope of this method (but within the scope of my class) I define my delegate with the same output type and input parameters as my method:
public delegate void myDelegate(string test);
I instantiate my delegate like so:
myDelegate md = new myDelegate(DelegateTest);
I can then kick off my method as many times as I like by BeginInvoking the delegate, and the methods will run side by side in separate threads.
md.BeginInvoke("Hello World", null, null);
md.BeginInvoke("Hello World Again", null, null);
md.BeginInvoke("Hello World A Third Time", null, null);
How do I now define an event and only kick off my method asynchronously when the event happens? Also, what are the limitations on what an event can be? Can more or less anything that happens on my computer be defined as an event or only certain things?
Edit: Say for example, after doing the above, I want to create an event and define this event as ‘the space bar has been pressed’. Every time the space bar is pressed, this is the event happening. When the event happens, I want to start my method asynchronously, I don’t want to start my method asynchronously if the space bar hasn’t been pressed.
How would I go about this?
Just use Invoke rather than BeginInvoke for synchronous calls.
EDIT: as per ThePower’s answer, you don’t need the Invoke, you can just call your delegate as if it were a function (because it is!).
EDIT2: You are actually trying to register an event handler. For this you don’t need to create your own delegate. An example for handling the KeyPress event in WinForms: