The regular Dns methods might cause a problem for your C# program because they use blocking mode to communicate with the remote DNS server. If you ran the example programs offered earlier in this section on the DNS classes, you may have noticed that it often takes a few seconds for the DNS information to be returned from the remote DNS server. This may not seem like much of a problem, but it can cause serious difficulties in Windows programs that allow the user to do other things at the same time. While the program is waiting for the DNS server response, the user is prevented from clicking any buttons or entering any information in TextBox fields. For some applications, this can mean unacceptable performance.
The Dns class provides the following asynchronous methods to allow your programs to perform asynchronous DNS function calls:
- •BeginGetHostByName()
- •BeginResolve()
- •EndGetHostByName()
- •EndResolve()
Each of the asynchronous methods parallels the equivalent synchronous method. At this time there is no asynchronous GetHostByAddress() call.
The methods are called in pairs. The Beginxxx method is called from the program and points to a delegate method, which contains the Endxxx method. For example, BeginResolve() uses the following format:
public static IAsyncResult BeginResolve(string hostname,AsyncCallback requestCallback, object stateObject)
The method uses three parameters:
- A string representation, hostname, of a hostname or IP address
- An AsyncCallback object, requestCallback, which defines the delegate
The AsyncCallback object is created to point to the delegate method used when the DNS results are returned. To do this, you must first create the AsyncCallback object, then assign the delegate method to it:
private AsyncCallback OnResolved;OnResolved = new AsyncCallback(Resolved);Object state = new Object(); . ., state); . } private void Resolved(IasyncDns.BeginResolve(addr, OnResolve dResult ar) { IPHostEntry iphe = Dns.EndResolve(ar); }
The OnResolved AsyncCallback object points to the delegate method Resolved, which will contain the EndResolve() method to complete the DNS call. The state object allows you to pass information to the delegate method. The EndResolve() method has this format:
public static IPHostEntry EndResolve(IasyncResult ar)
The IAsyncResult object ar is what refers the EndResolve() method to the original BeginResolve() method. The result of the EndResolve() method is the standard IPHostEntry object, which can then be broken down to extract the returned information, similar to the standard Resolve() method discussed earlier

No comments:
Post a Comment