Kredns
Kredns

Reputation: 37231

C# Delegates and Threads!

What exactly do I need delegates, and threads for?

Upvotes: 4

Views: 10946

Answers (8)

Matt Davis
Matt Davis

Reputation: 46052

Marc Gravell provided a nice answer for 'what is a delegate.'

Andrew Troelsen defines a thread as

...a path of execution within a process. "Pro C# 2008 and the .NET 3.5 Platform," APress.

All processes that are run on your system have at least one thread. Let's call it the main thread. You can create additional threads for any variety of reasons, but the clearest example for illustrating the purpose of threads is printing.

Let's say you open your favorite word processing application (WPA), type a few lines, and then want to print those lines. If your WPA uses the main thread to print the document, the WPA's user interface will be 'frozen' until the printing is finished. This is because the main thread has to print the lines before it can process any user interface events, i.e., button clicks, mouse movements, etc. It's as if the code were written like this:

    do
    {
        ProcessUserInterfaceEvents();
        PrintDocument();
    } while (true);

Clearly, this is not what users want. Users want the user interface to be responsive while the document is being printed.

The answer, of course, is to print the lines in a second thread. In this way, the user interface can focus on processing user interface events while the secondary thread focuses on printing the lines.

The illusion is that both tasks happen simultaneously. On a single processor machine, this cannot be true since the processor can only execute one thread at a time. However, switching between the threads happens so fast that the illusion is usually maintained. On a multi-processor (or mulit-core) machine, this can be literally true since the main thread can run on one processor while the secondary thread runs on another processor.

In .NET, threading is a breeze. You can utilize the System.Threading.ThreadPool class, use asynchronous delegates, or create your own System.Threading.Thread objects.

If you are new to threading, I would throw out two cautions.

First, you can actually hurt your application's performance if you choose the wrong threading model. Be careful to avoid using too many threads or trying to thread things that should really happen sequentially.

Second (and more importantly), be aware that if you share data between threads, you will likely need to sychronize access to that shared data, e.g., using the lock keyword in C#. There is a wealth of information on this topic available online, so I won't repeat it here. Just be aware that you can run into intermittent, not-always-repeatable bugs if you do not do this carefully.

Upvotes: 1

Eclipse
Eclipse

Reputation: 45533

They are useful for the same reason high-level languages are useful. You don't need them for anything, since really they are just abstractions over what is really happening. They do make things significantly easier and faster to program or understand.

Upvotes: 1

João Augusto
João Augusto

Reputation: 2305

Your question is to vague...

But you probably just want to know how to use them in order to have a window, a time consuming process running and a progress bar...

So create a thread to do the time consuming process and use the delegates to increase the progress bar! :)

Upvotes: 0

Mark Brittingham
Mark Brittingham

Reputation: 28875

Concrete examples always help me so here is one for threads. Consider your web server. As requests arrive at the server, they are sent to the Web Server process for handling. It could handle each as it arrives, fully processing the request and producing the page before turning to the next one. But consider just how much of the processing takes place at hard drive speeds (rather than CPU speeds) as the requested page is pulled from the disk (or data is pulled from the database) before the response can be fulfilled.

By pulling threads from a thread pool and giving each request its own thread, we can take care of the non-disk needs for hundreds of requests before the disk has returned data for the first one. This will permit a degree of virtual parallelism that can significantly enhance performance. Keep in mind that there is a lot more to Web Server performance but this should give you a concrete model for how threading can be useful.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1064114

Delegates act as the logical (but safe) equivalent to function-pointers; they allow you to talk about an operation in an abstract way. The typical example of this is events, but I'm going to use a more "functional programming" example: searching in a list:

List<Person> people = ...
Person fred = people.Find( x => x.Name == "Fred");
Console.WriteLine(fred.Id);

The "lambda" here is essentially an instance of a delegate - a delegate of type Predicate<Person> - i.e. "given a person, is something true or false". Using delegates allows very flexible code - i.e. the List<T>.Find method can find all sorts of things based on the delegate that the caller passes in.

In this way, they act largely like a 1-method interface - but much more succinctly.

Upvotes: 11

Rosstified
Rosstified

Reputation: 4087

I'd suggest have a search on these terms, there is plenty of information out there. They are pretty fundamental concepts, wiki is a high level place to start:

http://en.wikipedia.org/wiki/Thread_(computer_science)
http://en.wikipedia.org/wiki/C_Sharp_(programming_language)

Upvotes: 1

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422252

Delegates: Basically, a delegate is a method to reference a method. It's like a pointer to a method which you can set it to different methods that match its signature and use it to pass the reference to that method around.

Thread is a sequentual stream of instructions that execute one after another to complete a computation. You can have different threads running simultaneously to accomplish a specific task. A thread runs on a single logical processor.

Upvotes: 7

BBetances
BBetances

Reputation: 925

Delegates are used to add methods to events dynamically.

Threads run inside of processes, and allow you to run 2 or more tasks at once that share resources.

Upvotes: 2

Related Questions