This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.
The CallContext class can be thought of as "out-of-band" data or a channel hook. It operates at a thread level within an application domain. To cross application domain boundaries, objects must derive from the System.Runtime.Remoting.Messaging.ILogicalThreadAffinative interface, see Listing 25.18. An object registers with CallContext using the "key/value" paradigm. It is hooked to each method call and is part of IMessage, the _CallContext entry, which is sent over the wire. Using CallContext is simply a matter of calling the static methods SetData() and GetData().
The projects for this example are in the Sample4 folder. There is a standard library (CallContextLib) and two console applications (CallContextServer and CallContextClient). RemoteContextInfo is the class that will contain the out-of-band data. Figures 25.13 and 25.14 are the client and server output, respectively.
Listing 25.18: RemoteContextInfo.cs
[Serializable]
public class RemoteContextInfo : ILogicalThreadAffinative
{
private string machineName = null;
private string clientDir = null;
public RemoteContextInfo()
{
machineName = Environment.MachineName;
clientDir = Environment.CurrentDirectory;
}
public string MachineName
{
get
{
return (machineName);
}
}
public string ClientDir
{
get
{
return (clientDir);
}
}
}
To get and set the call context data, simply use the following code:
RemoteContextInfo data = null;
data = new RemoteContextInfo();
CallContext.SetData("Client", data);
RemoteContextInfo data = (RemoteContextInfo)CallContext.GetData( "Client");
Figure 25.13: Client Output
Figure 25.14: Server Output
This is an ideal way for custom proxies or message sinks to pass information from the client to the server or vice versa, without intruding into the functionality of the application.
Conclusion
Hope this article would have helped you in understanding Call Contexts in .NET. See other articles on the website on .NET and C#.
|
The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer. |