.NET Remoting
The last two Nuts and Bolts articles focused on database related topics. This month we'll change gears and focus on something different. The focus of this month's article will be .NET remoting. We'll discuss what is .NET Remoting, how it compares to DCOM and Web services, and go through an example.
What is .NET Remoting?
.NET Remoting is an enabler for application communication. It is a generic system for different applications to use to communicate with one another. .NET objects are exposed to remote processes, thus allowing interprocess communication. The applications can be located on the same computer, different computers on the same network, or even computers across separate networks.
.NET Remoting versus Distributed COM
In the past interprocess communication between applications was handled through Distributed COM, or DCOM. DCOM works well and the performance is adequate when applications exist on computers of similar type on the same network. However, DCOM has its drawbacks in the Internet connected world. DCOM relies on a proprietary binary protocol that not all object models support, which hinders interoperability across platforms. In addition, have you tried to get DCOM to work through a firewall? DCOM wants to communicate over a range of ports that are typically blocked by firewalls. There are a ways to get it to work, but they either decrease the effectiveness of the firewall (why bother to even have the firewall if you open up a ton of ports on it), or require you to get a firewall that allows support for binary traffic over port 80.
.NET Remoting eliminates the difficulties of DCOM by supporting different transport protocol formats and communication protocols. This allows .NET Remoting to be adaptable to the network environment in which it is being used.
.NET Remoting versus Web Services
Unless you have been living in a cave, or are way behind in your reading, you have probably read something about Web services. When you read the description of .NET Remoting it may remind you a lot of what you're read about Web services. That is because Web services fall under the umbrella of .NET Remoting, but have a simplified programming model and are intended for a wide target audience.
Web services involve allowing applications to exchange messages in a way that is platform, object model, and programming language independent. Web services are stateless and know nothing about the client that is making the request. The clients communicate by transferring messages back and forth in a specific format known as the Simple Object Access Protocol, or SOAP. (Want to get some funny looks in the hallway? Stand around in the hallway near the marketing department with your colleagues and discuss the benefits of using SOAP).
The following list outlines some of the major differences between .NET Remoting and Web services that will help you to decide when to use one or the other:
- ASP.NET based Web services can only be accessed over HTTP. .NET Remoting can be used across any protocol.
- Web services work in a stateless environment where each request results in a new object created to service the request. .NET Remoting supports state management options and can correlate multiple calls from the same client and support callbacks.
- Web services serialize objects through XML contained in the SOAP messages and can thus only handle items that can be fully expressed in XML. .NET Remoting relies on the existence of the common language runtime assemblies that contain information about data types. This limits the information that must be passed about an object and allows objects to be passed by value or by reference.
- Web services support interoperability across platforms and are good for heterogeneous environments. .NET Remoting requires the clients be built using .NET, or another framework that supports .NET Remoting, which means a homogeneous environment.
Channels
Remote objects are accessed through Channels. Channels physically transport the messages to and from remote objects. There are two existing channels TcpChannel and HttpChannel. Their names give away the protocols that they use. In addition, the TcpChannel or HttpChannel can be extended, or a new channel created if you determine the existing channels do not meet your needs.
Create a Remotable Object
A remotable object is nothing more than an object that inherits from MarshalByRefObject. The following sample demonstrates a simple class to expose the omnipresent hello world. This object exposes a single method HelloWorld that will return a string. The only values that can be returned from methods are the classes in the .NET Framework that are serializable such as string and DataSet. In addition, if you need to return a user-defined object then the object needs to be marked as serializable.
Create a new C# class library project. Add a class called SampleObject and put in the following code. Add a reference to System.Runtime.Remoting in the project, otherwise the TcpChannel will not be found. Compile the class to make sure you have everything correct.
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace CodeGuru.Remoting
{
/// <remarks>
/// Sample object to demonstrate the use of .NET Remoting.
/// </remarks>
public class SampleObject : MarshalByRefObject
{
/// <summary>
/// Constructor
/// </summary>
public SampleObject()
{
}
/// <summary>
/// Return a hello message
/// </summary>
/// <returns>Hello world message</returns>
public string HelloWorld()
{
return "Hello World!";
}
}
}
Create a Server To Expose the Remotable Object
We need to create a server object that will act as a listener to accept remote object requests. For this example we will use the TCP/IP channel. We first create an instance of the channel and then register it for use by clients at a specific port. The service can be registered as WellKnownObjectMode.SingleCall, which results in a new instance of the object for each client, or as WellKnownObjectMode.Singleton, which results in one instance of the object used for all clients.
It is not necessary to create the server listener if you are planning to use IIS. For obvious reasons, IIS only supports the use of the HttpChannel. Create a virtual directory for your application and then put code to register your service in the Application_Start event.
For our example, we'll go ahead and create a server listener in case you don't have IIS. Since the service needs to be bound to an available port, for our example I chose 8080, which is a port that I know to be unused on my computer. You may need to choose a different port depending upon what ports you have available. To see a list of the used ports on your computer open a command prompt and issue the command "netstat --a". It may produce a long listing so make sure the command prompt buffer sizes are set to allow scrolling. Compile the class to make sure you have everything correct.
Create a new C# console application project. Add a class called SampleServer and paste in the following code. Add a reference to System.Runtime.Remoting in the project, otherwise the TcpChannel will not be found. In addition, add a reference to the project containing the SampleObject, otherwise the code will not compile because it won't know how to find a reference to SampleObject.
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace CodeGuru.Remoting
{
/// <remarks>
/// Sample server to demonstrate the use of .NET Remoting.
/// </remarks>
public class SampleServer
{
public static int Main(string [] args)
{
// Create an instance of a channel
TcpChannel channel = new TcpChannel(8080);
ChannelServices.RegisterChannel(channel);
// Register as an available service with the name HelloWorld
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(SampleObject),
"HelloWorld",
WellKnownObjectMode.SingleCall );
System.Console.WriteLine("Press the enter key to exit...");
System.Console.ReadLine();
return 0;
}
}
}
Create a Client To Use the Remotable Object
Now that we have our remotable object and a server object to listen for requests, let's create a client to use it. Our client will be very simple. It will connect to the server, create an instance of the object using the server, and then execute the HelloWorld method.
Create a new C# console application project. Add a class called SampleClient and paste in the following code. Add a reference to System.Runtime.Remoting in the project, otherwise the TcpChannel will not be found. In addition, add a reference to the project containing the SampleObject, otherwise the code will not compile because it won't know how to find a reference to SampleObject. Compile the class to make sure you have everything correct.
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace CodeGuru.Remoting
{
/// <remarks>
/// Sample client to demonstrate the use of .NET Remoting.
/// </remarks>
public class SampleClient
{
public static int Main(string [] args)
{
// Create a channel for communicating w/ the remote object
// Notice no port is specified on the client
TcpChannel chan = new TcpChannel();
ChannelServices.RegisterChannel(chan);
// Create an instance of the remote object
SampleObject obj = (SampleObject) Activator.GetObject(
typeof(CodeGuru.Remoting.SampleObject),
"tcp://localhost:8080/HelloWorld" );
// Use the object
if( obj.Equals(null) )
{
System.Console.WriteLine("Error: unable to locate server");
}
else
{
Console.WriteLine(obj.HelloWorld());
}
return 0;
}
}
}
Test the Remoting Sample
Once you have created the projects and successfully compiled each of them you are ready to try it out. Assuming you chose a free TCP/IP port for the service, start the server executable. After the server successfully starts it will result in a console window being displayed with the message "Press the enter key to exit". The server is listening so you are now ready to run the client. Executing the client should result in "Hello World!" being displayed in a separate console window. The client window will then close while the server remains open and available.
If you have multiple computers available to you on a network you could execute the server on one machine and the client on another just to prove to yourself that it really is remoting. In order to run on separate machines you would need to change the reference to localhost in the sample client to point to the appropriate location.
Summary
.NET Remoting is a powerful way to enable interprocess communication. It is more complicated to program against than Web services. You need to decide for yourself whether your standard architecture is to use .NET Remoting or Web services.
Parallel Computing with .NET Remoting
Eric Bergman-Terrell
.NET Remoting allows you to distribute computing across multiple machines with ease, with a surprisingly small amount of programming. In this article, Eric Bergman-Terrell creates an application called Digits of Pi, which calculates π to a ludicrously high precision using multiple machines computing in parallel. He's managed to calculate 10,000 digits in just under 12 hours with a modest amount of computing power. That's about 300 percent faster than one machine alone could have managed by itself.
After downloading the sample application source code (available in the Download file), open the Everything.sln solution. This solution contains the three projects needed to run the Digits of Pi application (Client, Server, and ServerLoader). The solution also contains a project named SimpleClient that I'll discuss later. Once Everything.sln is loaded, select Build | Batch Build... Press the Select All button and then press Build. After everything is built, it's time to install the software on your local machine, as well as the remote machines on your LAN.
On your local machine, create a folder and copy the following files into it:
Server\bin\Release\Plouffe_Bellard.dll
Client\bin\Release\DigitsOfPi.exe
On each remote machine, and the local machine, create a folder and copy the following files into that folder:
Server\bin\Release\Plouffe_Bellard.dll
ServerLoader\bin\Release\ServerLoader.exe
ServerLoader\ServerLoader.exe.config
Then run the ServerLoader.exe program. Needless to say, each machine will need to have the .NET Framework installed before running the ServerLoader and the Digits of Pi program.
After the ServerLoader program is running on all remote machines and the local machine, run the Digits of Pi program. Press Configure... (see Figure 1) and add the machine names of the local and remote machines. If you're not sure what a machine is named, look at the ServerLoader program—it displays its machine name on its form. If you're lucky enough to have a multiple-CPU system, you can enter that machine name once for each CPU. Just type the machine name followed by an @ sign, followed by a number. For example, if you have a two-CPU system named "Brainiac", type in the following machine names: " Brainiac@1" and "Brainiac@2". You don't have to enter multiple machine names for multiple CPU systems, but doing so will ensure that all the machine's CPUs are used to calculate π. After you've entered all the machine names, press OK.
Then specify the number of digits (see Figure 2 ) to calculate and press Calculate. Start with a small number of digits—the program takes more and more time to compute digits of π further and further to the right of the decimal point.
Figure 3 shows how the Digits of Pi program distributes the workload to the local and remote machines, using TCP/IP port 9000 to send requests and receive results. We'll explore the details of Remoting, the Plouffe_Bellard server object, the ServerLoader program, the SimpleClient program, and the Digits of Pi program next.
Remoting basics
.NET Remoting enables an object to communicate with other objects, regardless of whether they're running on the same computer or on remote computers. .NET Remoting is superficially similar to Web Services, but .NET Remoting is the better technology for applications like Digits of Pi that are entirely written in .NET programming languages, and run exclusively on machines running the .NET Framework. See " ASP.NET Web Services or .NET Remoting: How to Choose" in the "Resources" sidebar near the end of this article for a comparison of the two technologies.
You can access a remote object with .NET Remoting by following these steps:
- Create a .NET server object (DLL) that inherits from System.MarshalByRefObject. The server object will be run on the remote machines and the local machine too.
- Create a server loader program that loads the server object by calling RemotingConfiguration.Configure. The server loader program will also be run on the remote and local machines.
- Create a client program that accesses the server object with Activator.GetObject. You'll need to add a reference to the server object to compile this program. This client program will only be run on the local machine.
The server object
The server object calculates the specified nine digits of π. It's named Plouffe_Bellard because it uses Fabrice Bellard's enhanced version of Simon Plouffe's algorithm. While faster algorithms are available, the Plouffe-Bellard algorithm is very simple (less than 300 lines of source code), uses a small amount of memory, and is ideal for parallel execution because each set of nine digits can be computed independently. The Plouffe_Bellard.CalculatePiDigits method calculates the nine digits of π that start at the specified position. For example, CalculatePiDigits(1) returns the nine digits starting with the first digit: 141592653. CalculatePiDigits(10) returns the next nine digits starting with the tenth digit, and so on.
The ServerLoader
The ServerLoader program loads the server object, specifies the protocol and port used to access the server object over the LAN, listens for incoming calls from the client program, processes calls, and returns the results. Remarkably, all of this can be accomplished with just one line of code, by calling the RemotingConfiguration.Configure method with the path to a configuration file. The ServerLoader program loads a configuration file named ServerLoader.exe.config (see Listing 1). This configuration file specifies that the server object is loaded in SingleCall mode, which means that every incoming call is serviced by a new instance of the server object. If the server object were loaded in Singleton mode, every incoming call would be serviced by the same instance. The type attribute specifies the full type name of the server object (including the PB namespace) and the name of its assembly. The objectUri attribute specifies the endpoint of the object's Uniform Resource Identifier (URI). The <channel> element specifies that the server object will be accessed using the TCP protocol, port 9000.
Listing 1. ServerLoader.exe.config.
<configuration>
<system.runtime.remoting>
<application name = "ServerLoader">
<service>
<wellknown
mode="SingleCall"
type="PB.Plouffe_Bellard,Plouffe_Bellard"
objectUri="Plouffe_Bellard"/>
</service>
<channels>
<channel ref="tcp server" port="9000"/>
</channels>
</application>
</system.runtime.remoting>
</configuration>
SimpleClient
I created a program named SimpleClient to demonstrate how easy it is for a client program to access a server object on a remote machine. To run SimpleClient, first run the ServerLoader on a remote machine and run the SimpleClient.exe program on the local machine. Enter the remote machine name in the Remote Machine text box and press the Calculate button to compute the first nine digits of π . SimpleClient's CalculateButton_Click method contains all the code that the client needs to access the remote server (see Listing 2). The remote server is accessed with a URL made up of the remote machine name, the protocol (TCP), and the port number (9000). For example, the URL to access the server on my "Pentium 200" machine is tcp://Pentium 200:9000/ServerLoader/Plouffe_Bellard. After creating the URL, Activator.GetObject is called with the type of the server (Plouffe_Bellard) and the URL. Then the return value is cast to a Plouffe_Bellard object and it's ready for use. When its CalculatePiDigits method is called, the request is sent to the ServerLoader on the remote machine. Then the server object computes the digits. Finally, when the results come back to the client program, they're displayed in a text box.
Listing 2. SimpleClient code to access the remote server.
private void CalculateButton_Click(object sender,
System.EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
Plouffe_Bellard PiCalculator = null;
String MachineName = RemoteMachineTextBox.Text;
try
{
int port = 9000;
String URL = "tcp://" + MachineName + ":" +
port + "/ServerLoader/Plouffe_Bellard";
PiCalculator = (Plouffe_Bellard)
Activator.GetObject(typeof(Plouffe_Bellard), URL);
ResultsTextBox.Text = "3." +
PiCalculator.CalculatePiDigits(1);
}
catch(Exception)
{
MessageBox.Show(
"Need to run ServerLoader.exe on machine " +
MachineName, "Simple Client",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Cursor.Current = Cursors.Arrow;
}
The Digits of Pi client
The Digits of Pi client program is much more elaborate than SimpleClient. SimpleClient only computes the first nine digits of π by accessing the server object on one remote machine. Digits of Pi, on the other hand, computes the user-specified number of digits in parallel, using all of the remote and local machines specified in the Configure dialog (shown in Figure 1). The server objects are accessed in separate threads in order to keep the Digits of Pi GUI responsive to user interaction during the potentially lengthy calculation process.
Digits of Pi distributes the workload among all the available machines by using an array that breaks the job into nine-digit chunks. After the user presses the Calculate button, it creates a SolutionArray (see Figure 4). The SolutionArray has a SolutionItem element for each group of nine digits of π that will be calculated. When a server object has computed the group of nine digits specified by the m_Digit field, the digits are stored in the m_Results member. The m_MachineName member contains the name of the machine on which the server is running. The machine name is stored so that Digits of Pi can display the total number of digits calculated by each machine (see Figure 2).
In order to have the server objects calculate in parallel, Digits of Pi creates a thread for each server object and starts the thread calculating. Then it must wait for all the threads to finish calculating before the final results can be displayed. WaitHandles are useful for waiting for multiple threads. Digits of Pi uses a WaitHandle for each thread in order to wait for all threads to complete.
CalculationThread.Calculate (see Listing 3) is called to create a thread for each server object. It starts the thread running and then returns an AutoResetEvent, which is derived from WaitHandle. Each thread's AutoResetEvent is stored in an array, which is passed to WaitHandle.WaitAll. When a thread completes its calculations, it calls the Set method on its AutoResetEvent. When the last thread calls the Set method, the WaitAll call returns, and the digits of π are displayed.
Listing 3. CalculationThread.
public static WaitHandle Calculate(
SolutionArray solutionArray, String machineName)
{
CalculationThread calculationThread = new
CalculationThread(solutionArray, machineName);
Thread thread = new Thread(new
ThreadStart(calculationThread.Calculate));
thread.Start();
return calculationThread.calculationDone;
}
Each thread follows the same algorithm: While there's more work to do, the thread grabs the next SolutionItem, stores its server object's machine name in the SolutionItem, calculates the specified nine digits, and stores the result in the SolutionItem. This process continues until all the SolutionItems have been filled with results. See Listing 4 for the details.
Listing 4. CalculationThread.Calculate.
public void Calculate()
{
Plouffe_Bellard PiCalculator =
RemotePiCalculator.GetPiCalculator(
GetRealMachineName(machineName));
if (PiCalculator != null)
{
SolutionItem Item = null;
bool Abort;
do
{
Abort = solutionArray.Abort;
if (!Abort)
{
Item = solutionArray.GetNextItem();
if (Item != null)
{
Item.MachineName = machineName;
try
{
Item.Results =
PiCalculator.CalculatePiDigits(Item.Digit);
}
catch (Exception e)
{
Abort = true;
MessageBox.Show(
"Cannot access remote object on host " +
machineName + Environment.NewLine +
Environment.NewLine + "Message: " +
e.Message, Globals.ProgramName,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
UpdateStatisticsDelegate USD = new
UpdateStatisticsDelegate(
MF.UpdateStatistics);
MF.Invoke(USD, new Object[] {} );
}
}
} while (Item != null && !Abort);
calculationDone.Set();
}
}
Here's a blow-by-blow description:
- The GetRealMachineName removes the @1 pattern from multi-CPU machine names. For example, GetRealMachineName("Brainiac@1") returns "Brainiac". See the text in the dialog box in Figure 1 for an explanation of multi-CPU machine names.
- Once the real machine name is known, it's passed to RemotePiCalculator.GetPiCalculator, and the server object on that machine is then accessible via the PiCalculator variable.
- The Abort property is set if the user has pressed the Cancel button. If the Abort property is true, the thread stops calculating.
- The call to MF.Invoke allows the thread to safely update the statistics in the ListView (see Figure 2) even though that ListView was created by a different thread. In 32-bit Windows programming, it's a big no-no to manipulate controls in a thread other than the one that created them.
- Once the loop is complete (meaning that all specified digits of π have been computed, or the user pressed the Cancel button), the Set function of the thread's AutoResetEvent is called.
- When each thread has called its AutoResetEvent's Set function, the call to WaitHandle.WaitAll will return and the results will be displayed.
Thread synchronization
There are several places in Digits of Pi's code where errors would occur if the code were accessed simultaneously by multiple threads. For example, if two threads called SolutionArray.GetNextItem at precisely the same time, they might both end with the same item. That's why the GetNextItem method has the [MethodImpl(MethodImplOptions.Synchronized)] attribute, which ensures that only one thread can call it at a time. Making a method synchronized is a good strategy when every line of the method shouldn't be accessible by more than one thread at a time.
Since the MainForm.Calculate method has only one line that can't be accessed simultaneously by multiple threads, it calls Monitor.Enter before the line, and Monitor.Exit after the line. Monitor.Enter will block if the line is already running in another thread. While the entire function could have been made synchronized, protecting only the lines that need to be protected from multi-thread access will tend to result in better performance.
Objects derived from System.Windows.Forms.Control (for example, Buttons, TextBoxes, RichTextBoxes, Labels, ListBoxes, ListViews, and so on) should only be manipulated by the thread that created them. To safely manipulate a Control derivative from a thread that didn't create it, first put the manipulation code in a method and declare a delegate for that method:
delegate void SetResultsTextDelegate(String Text);
private void SetResultsText(String Text)
{
ResultsRichTextBox.Text = Text;
}
Then call the method indirectly, using Form.Invoke:
SetResultsTextDelegate SRTD = new
SetResultsTextDelegate(SetResultsText);
Invoke(SRTD, new object[] { "" } );
The Invoke method calls the method from the thread that created it, with parameters corresponding to the elements in the object array.
Summary
.NET Remoting is a simple and convenient mechanism for executing code on remote (and local) machines. All that's necessary is to package the code in a .NET object, write a program to load the object and listen for requests, and call Activator.GetObject in the client program. If you have some idle machines on your LAN, it's easy to put them to work to solve a problem in parallel. Just remember to use the proper thread synchronization mechanisms to keep one thread from stepping on another thread's toes.

0 Comments:
Post a Comment
<< Home