Showing posts with label threading. Show all posts
Showing posts with label threading. Show all posts

Monday, January 28, 2008

C# Events

using System;
using System.Windows.Forms;
namespace EventsMadeSimple
{
    public partial class Form1 : Form
    {
        SimpleClass SimpleObject = new SimpleClass(); // create a new SimpleClass object
        public Form1() // Form1 constructor
        {
            InitializeComponent();
            Load += new EventHandler(Form1_Load); // add Form1's Load event handler
            // add our object's event handler
            SimpleObject.SimpleEvent += new OnSimpleEvent(SimpleEventOccurred);
        }
        void Form1_Load(object sender, EventArgs e)
        {
            SimpleObject.SimpleMethod(); // call the SimpleObject's method
        }
        private void SimpleEventOccurred() // method is called when the event is raised
        {
            listBox1.Items.Add("SimpleEvent was fired at " + DateTime.Now.ToString());
        }
    }
    public delegate void OnSimpleEvent(); // delegate
    public class SimpleClass
    {
        public event OnSimpleEvent SimpleEvent; // event
        public void SimpleMethod()
        {
            SimpleEvent(); // raise the event
        }
    }
}
 

There are two classes here. The standard windows generated Form1 and SimpleClass. SimpleClass is our own class with one event and one method.

Inside Form1 we've created a new instance of SimpleClass called SimpleObject.

In Form1's constructor, we've added an event handler (this makes it 'listen' for the specified event and call the specified method) for loading of Form1, and another for our SimpleObject's event. This calls the SimpleEventOccurred method in Form1 when the event is raised.

In Form1's load method we call SimpleObject's SimpleMethod, which is where the event gets raised. This method could be called from anywhere but I've placed it in the Load so it happens immediately when you run the project.

How easy was that?

Experiment Suggestions

Passing parameters: You will often see something similar to this in the signatures of methods called by events:

(object sender, EventArgs e)

If you want to do this or anything similar you will also need to give your delegate the same signature and pass valid paramaters when raising the event i.e.

public delegate void OnSimpleEvent(object sender, EventArgs e);

......

SimpleEvent(this, EventArgs.Empty); // raise the event

 

Custom EventArgs: You can create your own class that inherits from System.EventArgs

public class SimpleEventArgs : EventArgs { }

and pass an instance of this class in your parameters. This class can obviously have its own propeties/methods/constructors etc that can be manipulated and/or made accessible to the receiving method.


Return type: The method that gets called by the event handler (private void SimpleEventOccurred() in our case) can return a value type. To do this you will need to specify the same type in your delegate declaration. The call to SimpleEvent() will then be returned a value of type you specified.

Source

more info

Another simple example

Saturday, May 5, 2007

BackgroundWorker Component

MSDN Best Example example1 example2

The System.Threading Namespace

The System.Threading namespace provides classes and interfaces that enables multithreaded programming. This namespace includes a ThreadPool class that manages groups of threads, a Timer class that enables a delegate to be called after a specified amount of time, and a Mutex Class for synchronizing mutually-exclusive threads. System.Threading also provides classes for thread scheduling, wait notification, and deadlock resolution.

Some of the important classes in System.Threading namespace is discussed below.

Thread - Represents threads that execute within the runtime, to create and control threads.

ThreadPool - Posts work items to the thread pool. Queue work items for execution on the first available thread from the thread pool. One OS thread pool per process. Efficient use of thread resources.

Timeout - Contains timeout values for the system

Times - Specifies a delegate to be called at a specified time. The wait operation is performed by a thread in the thread pool.

Monitor - Provides the synchronization of threading objects using locks and wait/signals.

Mutex - A synchronization primitive that can also be used for interprocess synchronization. Wait can be used to request ownership of the mutex. The state of the mutex is signaled if no thread owns it.

The thread that owns a mutex can specify the same mutex in repeated wait function calls without blocking its executions. It must release the mutex as many times ti release ownership. If a thread terminates normally while owning a mutex, the state of the mutex is set to signaled and the next waiting thread gets ownership.

Life Cycle Methods

Starting a Thread

The thread class of System.Threading Namespace represents a thread object. By using class object, we can create new threads, delete, pause and resume threads. The thread class creates a new thread and Thread.Start method starts a thread.

thread = new Thread(new TreadStart( writeData )); thread.start();

where writeData is a function which will be executed by the program.

Killing a Thread

Thread class's Abort method is called to kill a thread permanently. Make sure IsAlive is called before Abort.

if(thread.IsAlive)

{

thread.Abort();

}

Pausing a Thread

Thread.Sleep method can be used to pause a thread for a fixed period of time.

thread.Sleep();

Suspending a Thread

The Suspend method of the thread class suspends a thread. The thread is suspended until Resume method is called.

if( thread.ThreadState == ThreadState.Running) { thread.Suspend(); }

Resume a suspended Thread

The Resume method is called to resume a suspended thread. If the thread is not suspended, there will be no effect of Resume method.

if(thread.ThreadState == ThreadState.Suspended) { thread.Resume(); } Source