art of good component writing involves designing and developing components with the idea that developers other than you will use them. A good practice is to use conventions that are familiar and, if possible, industry standard. In this article, you will learn how to build asynchronous functionality directly into your business objects using a method-naming scheme already in use by asynchronous delegates, asynchronous Web services, and various other asynchronous classes throughout the .NET Framework. In the end, your business objects will be powerful, scalable, and follow a familiar .NET pattern.
Before you design these new objects, let's review how to call an object's method using an asynchronous delegate. First, set up a simple class to serve as a business object and that will evolve throughout this article.
The Business Object
Call this class FileFunctions and give it one method: MoveFiles
. This method receives two strings as its arguments: sourceFolder
. Quite simply, the method accesses the directory location identified by the sourceFolder
argument, and moves all files within to the directory identified by the destinationFolder
argument. The return variable for this method is a Boolean that indicates success or failure of this operation. The actual business functionality will not be described or listed here.
In VB .NET
public bool MoveFiles(string sourceFolder,
// Functionality for file moving.
Public Function MoveFiles( _
ByVal sourceFolder As String, _
ByVal destinationFolder As String)
' Functionality for file moving.
To perform this function in a normal synchronous fashion, instantiate the class and set a Boolean variable to the method call, sending in the required arguments. In fact, you can do this all in one line.
|You can avoid waiting for your calls to complete by using an asynchronous delegate in the conventional manner to call an operation on its own thread.|
In VB .NET
bool b_Success =
Dim b_Success As Boolean = _
New FileFunctions().MoveFiles( _
"c:\\BeforeFolder ", _
This works just fine, except for the fact that the calling program just sits there until this operation is complete and a success or failure flag has been returned. So let's avoid this wait by using an asynchronous delegate in the conventional manner to call this operation on its own thread.
|This article assumes a basic knowledge of delegates, the .NET Framework's type-safe version of C++ function pointers.