Docsity

Event-Driven Programming Lecture 1 – C# & .NET Notes, Examples and Diagrams, Study notes of Programming Languages

Toggle sidebar
bg1
TOPIC 1: INTRODUCTION TO EVENT-DRIVEN PROGRAMMING
Week
Lecture length
Learning outcome
Week 1
3 hours
LO1
LEARNING OBJECTIVES
By the end of this chapter a learner should be able to:
● Define event-driven programming and an event.
● Identify an event source, an event handler, a publisher and a subscriber.
● Distinguish sequential execution from event-driven execution.
● Interpret a simple Windows Forms event handler.
● Classify an event by the category it belongs to.
1.1 Meaning of Event-Driven Programming
Event-driven programming is a programming approach in which the flow of an application is
determined by events that occur while the application is running. These events come from a user,
the operating system, another program, a timer, a network connection or a message service.
An event does not have to be a mouse click. It can be a form opening, a key being pressed, a
timer reaching its interval, a file finishing a download, an order being created or a message
arriving from another service. The application has code prepared to respond when the event
occurs.
1.2 Core Terms
Event
An event is an occurrence that a program can detect and respond to. Events represent user
actions, changes in data, completion of work or communication from another part of a system.
Example event
What caused it
Click
A user presses a button.
TextChanged
The content of a text box changes.
Form Load
A graphical form opens.
Timer Tick
A timer reaches its interval.
Message received
A message arrives from another service.
Payment completed
A payment process reports success.
Event Source
The event source is the object or component from which an event originates. In a Windows
Forms program, a Button control is the source of a Click event. A Timer is the source of a Tick
event. In a distributed application, a payment service is the source of a PaymentCompleted event.
The source identifies where the event came from. One application contains many possible event
sources, each capable of producing different events.
pf3
pf4
pf5

Partial preview of the text

Download Event-Driven Programming Lecture 1 – C# & .NET Notes, Examples and Diagrams and more Study notes Programming Languages in PDF only on Docsity!

TOPIC 1: INTRODUCTION TO EVENT-DRIVEN PROGRAMMING

Week Lecture length Learning outcome Week 1 3 hours LO

LEARNING OBJECTIVES

By the end of this chapter a learner should be able to:

● Define event-driven programming and an event. ● Identify an event source, an event handler, a publisher and a subscriber. ● Distinguish sequential execution from event-driven execution. ● Interpret a simple Windows Forms event handler. ● Classify an event by the category it belongs to.

1.1 Meaning of Event-Driven Programming

Event-driven programming is a programming approach in which the flow of an application is

determined by events that occur while the application is running. These events come from a user,

the operating system, another program, a timer, a network connection or a message service.

An event does not have to be a mouse click. It can be a form opening, a key being pressed, a

timer reaching its interval, a file finishing a download, an order being created or a message

arriving from another service. The application has code prepared to respond when the event

occurs.

1.2 Core Terms

Event

An event is an occurrence that a program can detect and respond to. Events represent user

actions, changes in data, completion of work or communication from another part of a system.

Example event What caused it

Click A user presses a button.

TextChanged The content of a text box changes.

Form Load A graphical form opens.

Timer Tick A timer reaches its interval.

Message received A message arrives from another service.

Payment completed A payment process reports success.

Event Source

The event source is the object or component from which an event originates. In a Windows

Forms program, a Button control is the source of a Click event. A Timer is the source of a Tick

event. In a distributed application, a payment service is the source of a PaymentCompleted event.

The source identifies where the event came from. One application contains many possible event

sources, each capable of producing different events.

Event Handler

An event handler is a method that contains the code to run when a particular event occurs. The

event states that something happened; the handler contains the response. A handler displays a

message, validates input, updates data, starts another operation or changes part of the interface.

private void btnLogin_Click( object sender, EventArgs e) { lblStatus.Text = "Login button clicked"; } The handler is named btnLogin_Click. It runs when the associated Login button produces a Click event. The statement inside the method changes the text displayed by lblStatus. Publisher and Subscriber A publisher is an object that announces or raises an event. A subscriber is an object or method that has registered to receive that event. The publisher does not need to know every detail of what subscribers will do after receiving the notification. This separation lets different parts of a program respond to the same occurrence. Basic publisher-subscriber model After an online payment succeeds, one part of the system can create a ticket, another can send an email and another can record the sale. All three actions are responses to the same payment event. Event Loop An event loop is the mechanism that keeps an application ready to receive events and dispatch the correct response. In most graphical frameworks, the programmer does not write the full event loop. The framework manages the waiting and dispatching, while the programmer writes the handlers for the events that matter to the application. Event source Event Event loop Handler 1 Handler 2 Who causes it What happened Handler 3 Delivers the notification

The two styles appear inside the same application. An event handler contains several statements that execute sequentially. Event-driven programming does not remove normal program flow; it determines when particular blocks of code run.

1.5 Event-Driven Programming in C# and .NET

.NET provides built-in support for event-driven programming. C# uses delegates and events to connect a notification to one or more methods. Windows Forms provides controls such as Button, TextBox, CheckBox, ComboBox and Timer that expose events. ASP.NET Core handles web requests through routes, controllers, endpoints and middleware, while message systems notify services when new messages arrive.

1.6 A First Windows Forms Event

A form contains a TextBox named txtName, a Button named btnWelcome and a Label named

lblMessage. The program displays a greeting after the user enters a name and clicks the button.

private void btnWelcome_Click( object sender, EventArgs e) { string studentName = txtName.Text; lblMessage.Text = "Welcome " + studentName; } The method does not run continuously. It runs after the Click event occurs. txtName.Text reads what the user typed. The result is assigned to lblMessage.Text, changing what appears on the form.

The sender and EventArgs Parameters

Many .NET event handlers contain two parameters: sender and EventArgs e. The sender

parameter refers to the object that raised the event. EventArgs carries information associated

with the event. Some events need little extra information, while others use a more specific event-

argument class containing details about what happened.

Event Subscription

An event handler must be connected to an event before it can respond. In C#, the += operator

subscribes a handler to an event. Windows Forms can also create this connection through the

Visual Studio designer.

btnWelcome.Click += btnWelcome_Click;

This statement reads as: when btnWelcome raises its Click event, call btnWelcome_Click.

Chapter 2 explains why this connection works and how delegates are involved.

One Event Can Produce Several Responses

An event can have more than one subscriber. When an order is completed, one subscriber can

send a receipt, another can reduce stock and another can record the transaction. Each subscriber

performs its own task after the same event.

1.7 Event-Driven and Asynchronous Programming

Event-driven programming and asynchronous programming are related but are not the same idea.

Event-driven programming focuses on responding to occurrences. Asynchronous programming

focuses on starting work without unnecessarily blocking the current flow while waiting for that

work to finish.

Clicking a Download button is an event. The download itself then runs asynchronously so the

interface remains usable.

1.8 Common Uses of Event-Driven Programming

Area Typical events Desktop software Button clicks, menu selections, form load, keyboard input Web applications HTTP requests, form submissions, authentication actions Mobile applications Touches, notifications, sensor changes, location updates Games Key presses, collisions, timer events, score changes IoT systems Sensor readings, threshold changes, device messages Distributed systems Order created, payment completed, message received

1.9 Benefits and Challenges

Event-driven programs suit interactive systems because they respond to actions when those actions occur. The approach separates the component that announces an event from the components that react to it, which makes software easier to extend because new handlers are added for new responses. The approach also creates challenges. The order of events is harder to follow than a short sequential program. A large program contains many handlers, and slow work inside a handler makes a user interface appear frozen. Clear naming, clear structure, testing and asynchronous techniques manage these problems. REAL-WORLD EXAMPLEs 1.ATM An ATM waits for actions from the customer. Inserting a card, entering a PIN, selecting Withdraw and pressing Cancel are separate events, each with a different handler. The program does not execute every possible action in one fixed sequence because the next action depends on the customer.

2. Student Portal When a student clicks Submit Assignment, the button or web request is the event source. A submission event occurs, the system checks the file and records the submission, then the interface displays confirmation. Other services can respond by sending an email or recording an audit entry. 3. Ticket Purchase A successful payment acts as an event for several parts of a ticketing system. The ticket component generates a ticket, the email component sends confirmation and the reporting component records the sale.

1.10 Reading a Simple Event Handler

private void btnSave_Click( object sender, EventArgs e) { string name = txtName.Text; lblStatus.Text = "Saved: " + name; } The event source is btnSave. The event is Click. btnSave_Click is the event handler. The first statement reads text from txtName, and the second updates lblStatus. Reading event-driven code starts with identifying the source, the event, the handler and the visible or logical response.