Click here to Skip to main content
Click here to Skip to main content

Asynchronous Thread Calls With Delegates

By , 23 Mar 2012
 

Introduction 

This is a small example for doing asynchronous operations on Windows Forms by using delegates.  As this article is mostly about using Asynchronous Thread Calls, there is nothing really fancy going on inside the application. But this article can be a useful piece of information in async operations. The required code explanatios can be found inside the project itself. 

Purpose, Pros, and Cons 

This actually is a different - and probably a rare approach for working on asynchronous operations. Basically, delegates are used to invoke different non-returning (void) functions. By doing this, you may achieve smoother and less "laggy" experience on your applications, when you need to make some heavy duty work such as large number calculations, massive I/O operations and even for working with web based applications (such as using web services etc.)

As a simple example, when calling loads of data from a database, it may take a while to load and show your data to user. In this scenario, user may think the application is in a deadlock or there has been a failure in the application. To prevent these, the user needs to see what's actually happening in the background. By using this method, the user will be able to make other operations (if possible) on the form, move the form itself, resize it and every other things that can be done.

However, there is one main drawback for this method, and that would be the part where Control.CheckForIllegalCrossThreadCalls = false; goes. Even though Microsoft has allowed developers to bypass Illegal Cross Thread Calls Checking, using it is considered as bad practice by most of the developers. But why it is a bad practice and what does it do actually?

At runtime phase of the application, .NET Framework checks if a control/object is being accessed and/or manipulated in an unsafe manner from another thread or threads. So basically, this controlling property comes in when there are multiple threads in an application. The property allows us to turn off the runtime check. That's why this is mostly considered as bad practice by most of the developers beacuse it is nothing but ignoring the problem that have or will occur. As most of us will agree, ignoring the problem is not the way to solve it.

So, what's the problem here? Actually there is no one problem. There might be all sorts of problems that can happen when multiple threads (or users) are trying to access and manipulate an object simultaneously, which is something even worse. So basically, the main problem is concurrency.

You can see the real trouble of illegal cross thread calls in the example below. 

Let's say we have a variable called result which its type is integer. The following code multiplies its value by 2 and writes the new value to the same variable. So, even if we have more than one thread and if the threads are executed sequentially (synchronously), we will not have any problems at all. The process steps are as shown below.

result*=2;

However, if the threads are not executed sequentially, things are quite different...

As a conclusion, using Control.CheckForIllegalCrossThreadCalls is totally up to you and the structure of your application. Just to be safe, keep in mind that this property can also cause great security problems as well. So you better think twice before using it.

Using the code 

Mostly, the whole thing is working through delegates and simple methods. Delegates are used to send invoke messages. In this example, there are two main methods. The first one is DoStuff(), which obviously is for doing the async work, and the second one is EndProcess() which takes IAsyncResult object as parameter. In DoStuff() method, nothing fancy is given in the example. Only changing background color and dynamically inreasing value of a variable. 

public void DoStuff()
{
    for (int i = 0; i...)
    {
         //...
    }
}

Nothing extra is used in the application like external resources, images etc. The source code or the demo application can be downloaded and run easily. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Selim Sertaç BALCI
Software Developer
Turkey Turkey
Member
Software Engineer, has been working on multiple platforms such as Apple, PHP and .NET Framework. Addicted to iOS development.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberU@00726 Jul '12 - 22:57 
Good Work it's working fine
QuestionBackgroundWorker?memberjohannesnestler19 Mar '12 - 4:02 
Ok, But how is this better then using a simple BackgroundWorker (without messing with "CheckForIllegalCrossThreadCalls")? I don't see your point...
AnswerRe: BackgroundWorker?memberradioman.lt19 Mar '12 - 6:01 
because there is no point ;} point.Enabled = false;
d{^__^}b - it's time to fly

GeneralRe: BackgroundWorker?memberjohannesnestler20 Mar '12 - 9:39 
funny answer - accepted Rose | [Rose] I don't know why I wanted to see a point, when there is none... D'Oh! | :doh: CheckForIllegalCrossJokeCalls = false.
GeneralRe: BackgroundWorker?memberSelim Sertaç BALCI20 Mar '12 - 9:45 
The point is about using this method is unsafe and unreliable. Sorry for both of you, none of you guys got it. It was obvious.
GeneralRe: BackgroundWorker?memberradioman.lt20 Mar '12 - 10:31 
Big Grin | :-D
d{^__^}b - it's time to fly

GeneralRe: BackgroundWorker?memberjohannesnestler21 Mar '12 - 8:24 
"CheckForIllegalCrossJokeCalls = false"? Mine was turned off - sorry Big Grin | :-D
GeneralRe: BackgroundWorker?memberSelim Sertaç BALCI21 Mar '12 - 9:59 
Ok now, you should be nice. There is no need to be sarcastic. Of course you can criticise my work and make comments, but you shall not make fun of it, be sarcastic about it or despise my work or me as a person. Behave yourself and show some respect for the work, even if it is not good.
GeneralRe: BackgroundWorker?memberjohannesnestler22 Mar '12 - 0:43 
??? I'm not shure what you mean. But: I respect your work and you as a person, I wasn't joking on you, just answering to funny "no point" comment. I wouldn't comment if I wouldn't be interested on the topic - and I think your work (writing article, research, answering funny/stupid comments)is good. Rose | [Rose]
QuestionCode snippets with explanationmentorMd. Marufuzzaman16 Mar '12 - 20:20 
It would very nice to add some code snippets with explanation on how it works. Thumbs Up | :thumbsup:
Thanks
Md. Marufuzzaman


I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.

QuestionMissing filesstaffSmitha Vijayan16 Mar '12 - 12:18 
Hello Selim,
 
Could you please add the missing images and downloads?
 
Thanks
Smitha
Are you an aspiring author? Read how to submit articles to CodeProject: Article Submission Guidelines[^]
 
More questions? Ask an editor here.../xml>

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 23 Mar 2012
Article Copyright 2012 by Selim Sertaç BALCI
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid