воскресенье, 14 марта 2010 г.

C# 4.0 events. Small implementation change

C# 4.0 is going to change the way how event handlers addition and removal is implemented. From it birth C# compiler used to add special accessor methods to every event which didn’t have its own accessors declared. For thread safety those auto accessors had MethodImpl(MethodImplOptions.Synchronized) attribute defined on them. Using that attribute on publicly accesible methods is considered harmful because at runtime those methods are wrapped in lock(this) or lock(typeof([TypeDeclaringTheEvent])) for static events which, in its turn, is a bad practice as well.

In C# 4.0 event accessors don't use explicit locking, but implement what can be considered as optimistic locking. Look at the following:

//pre 4.0
[MethodImpl(MethodImplOptions.Synchronized)]
public void add_Disposed(EventHandler value)
{
    this.Disposed = (EventHandler) Delegate.Combine(this.Disposed, value);
}

// 4.0
public void add_Disposed(EventHandler value)
{
    EventHandler handler2;
    EventHandler disposed = this.Disposed;

    do
    {
        handler2 = disposed;
        EventHandler handler3 = (EventHandler) Delegate.Combine(handler2, value);
        disposed = Interlocked.CompareExchange(ref this.Disposed, handler3, handler2);
    }
    while (disposed!= handler2);
}

With the new algorithm we don't have to have one private object for each public event just to protect them from lockin issues. Besides that it is a little bit lighter and more performant. Delegate type itself hasn't changed at all. Delegates have been immutable reference types from the very begining. The only question I have: Why they didn't do that in the first place!?

More details in C# compiler team member's blog:
Field-like Events Considered Harmful
Events get a little overhaul in C# 4, Part II: Semantic Changes and +=/-=

воскресенье, 7 марта 2010 г.

What I’d like to see in C# 5.0

Axum, an experimental language, has such a feature as async methods. In such methods interaction with  interaction points and APM based API happens asynchronously.
Besides that there are signs that in the future C# will support resumable methods. Luca Bolognese opened up some details at the PDC 2009 session Future of C# and VB. Fast-forward to 50:00 where he shows experimental yield keyword in the method returning Async<T>.
That’s great news because with what we have now  if you want to make long running call not keeping your thread waiting/doing nothing/consuming  memory you have to put all your logic in callback methods calling each other. With resumable methods such code would be much  easier to write, read and refactor, and the exception handling would look like  synchronous, stack based.

But being excited about the feature:

  • I don’t like the idea of introducing a new type (Async<T>) when we already have Task and Task<T> types
  • I’d like C# to recognize not only APM pattern based API but methods and properties that return Task or Task<T> as well. If you compare Task and IAsyncResult you’ll see that a Task based asynchronous API is much simpler, cleaner and easier to implement. Compare the next two variations:

    //Task based API
    public Task  UploadData(string uri, string data)  { … }
    public Task<string> DownloadData(string uri) { … }
    public Task<int> TotalNumberOfRows { get { … } }

    //APM based API
    public IAsyncResult BeginUploadData(string uri, string data, AsyncCallback callback, object context)  { … }
    public void EndUploadData(IAsyncResult ar)

    public IAsyncResult BeginDownloadData(string uri, AsyncCallback callback, object context) { … }
    public string EndDownloadData(IAsyncResult ar)

    public IAsyncResult BeginGetTotalNumberOfRows(AsyncCallback callback, object context) { … }
    public int EndGetTotalNumberOfRows(IAsyncResult ar)

  • I’d like C# to recognize extension methods that implement APM or Task based API

суббота, 27 февраля 2010 г.

EqualityComparer for C# 3.0 Expressions

.NET Expression classes let us perform only reference equality checks on them. But sometimes we need to check the true value equality.  As part of my attempt to build autocacher for LINQ TO SQL compiled queries I created an equality comparer that implements IEqualityComparer<Expression> interface. It lets me, for example, to use an Expression as a key in a dictionary. The implementation is .NET 3.5 specific  and based on the example ExpressionVisitor class from MSDN. As a bonus  there are extensions to the Expression class in the project so that you can visit and rewrite  expressions without deriving from ExpressionVisitor. It can be very handy in simple scenarios.

ExpressionEqualityComparer.zip

p.s. BTW in .NET 4.0 they made  the ExpressionVistor class public.  In .NET 3.5 it  was internal.

среда, 10 февраля 2010 г.

LINQ TO SQL and asynchronous IO

LINQ TO SQL doesn’t inherently support asynchronous IO. It is unfortunate, because non-blocking IO is a way to get great scalability on server side whether you do it directly with APM,   CCR Iterators  and APM adaptors, Jeffrey Richter's AsyncEnumerator, TPL iterators'  integration with APM,  or even Axum which natively recognizes APM methods.

Well there is actually a small hole through which we can use APM but in a very restrictive way.
The best  tool to experiment with L2S is LinqPAD. Point it at Northwind database and try next “statement” query:

var query = from e in Employees
   where e.EmployeeID == 1
   select e;

System.Data.Common.DbCommand cmd = this.GetCommand(query);
try
{
 this.Connection.Open();
 System.Data.Common.DbDataReader reader = cmd.ExecuteReader();
 IEnumerable employees = this.Translate(reader);
 
 //using results
 Employees employee = employees.First();
 employee.Dump();
}
finally
{
 this.Connection.Close();
}

Instead of ExecuteReader we can use BeginExecuteReader and EndExecuteReader methods.  Wrap it in an convenient extension method for DataContext class and it seams we solved the problem. No.. Here is the list of problems we still have:

  • eager loading of many-to-one and one-to-many relations of the  entity in question doesn’t work with our method
  • to fulfil some queries L2S has to send more than one SQL commands to the server, but DataContext.GetCommand returns only the first one
  • L2S doesn’t support asynchronous lazy loading of  many-to-one, one-to-many  and Link<T> based properties of an entity
  • L2S doesn’t support asynchronous compiled queries
  • besides querying L2S doesn’t support  submitting changes asynchronously
  • and don’t forget about transactions

The list looks like a show stopper. But if you really  need to use APM with L2S and are not going to  eager load relations of the entity you want to query and sure that your  query will generate only one SQL command and won’t be surrounded by a transaction then you  should use it because parallelism and asynchronicity  is the way to performance and scalability.

воскресенье, 7 февраля 2010 г.

.NET threads and stack memory

Normally when an unmanaged thread is created 1 MB of virtual address space is reserved and 4 KB (a page) is committed for its stack. Reserved here is an important word, because reservation allocates no physical storage but only well.. reserves a range of virtual memory.  It guaranties continuousness of the memory required for threads’ stacks. Allocation of the real storage (committing) happens as the stack grows, page by page. 
But as address space in a process is usually limited by 2 GB  the more threads you create the less virtual address space is left. For example, a thousand of threads can consume a half of the available  virtual memory of the process. 
But recently I have found that the things are different in the managed world. When a managed thread created  1 MB of memory is reserved and committed for its stack before it starts. There is no difference between a managed thread and an unmanaged one regarding virtual memory space consuming but the early committing  brings the whole system closer to the commit limit which is “the sum of physical memory and the sizes of the paging files”.
It is one more reason not to create threads if you can. Use ThreadPool, Tasks or  async IO instead.

You can read more about the reasons behind the CLR team’s decision,
what Windows memory limits are and how  Processes and Threads consume memory.

среда, 27 января 2010 г.

вторник, 17 ноября 2009 г.

понедельник, 16 ноября 2009 г.

Spirals

In COM times IDispatch and IExpando interfaces were used to enable COM components written in strongly typed languages to enter the world of VisualBasic and JScript.

Now DynamicObject and ExpandoObject let C# not only to interoperate with dynamic languages but to be dynamic itself.

среда, 11 ноября 2009 г.

Combining ASP.NET AJAX component descriptors

If you have worked with ASP.NET AJAX you know that every instance of ScripCompomentDescriptor created on server side generates startup javascript code at the end of the page. Something like this:

Sys.Application.add_init(function() {
$create(AjaxControlToolkit.DynamicPopulateBehavior, {"PopulateTriggerID":"ctl00_SampleContent_Label1","ServiceMethod":"GetHtml","ServicePath":"/AJAX/AjaxControlToolkit/Samples/DynamicPopulate/DynamicPopulate.aspx","UpdatingCssClass":"dynamicPopulate_Updating","id":"dp1"}, null, null, $get("ctl00_SampleContent_Panel1"));
});





And the more instances you create the bigger your page size. You should not bother if there are only a few components on your page or when you turn on compression for dynamic content. But if dynamic compression is not an option declaration of dozens of ajax script controls or behaviours can easily twice the page size. ASP.NET AJAX doesn’t have a built-in way of combining multiple ajax component declarations so I had to resort to our old friend Reflection.

All combining logic I’ve put into the class derived from System.Web.UI.ScriptManager. Classes ScriptControlBase and ExtenderControlBase intercept script descriptors registration and register their in our special ScriptManager. The ScriptManager at last possible point, before ASP.NET renders registered startup scripts, combines registered script descriptors, generates necessary javascript code and registers it as startup script. That’s it.



Combined script controls (or behaviours) creation looks like this:


Sys.Application.add_init(function()
{
$createMultiple(TestWeb.UserCard,['ctl03_item','ctl04_item','ctl05_item','ctl06_item','ctl07_item','ctl08_item','ctl09_item','ctl10_item'],
{serviceMethod:["GetUserInfo"],servicePath:["/CombinedDescriptorsExample/Services/Users/GetUserInfo.svc"],userId:[123,0,1,[1,6],2,[2,7],3,3,4,4,0,5]},
null,
null);
});





$createMultiple is a function similar to $create, but it creates.. multiple components of a script control/behaviour type.

It takes 5 arguments: name of a script control type to create, array of html elements’ ids, object describing properties setters, events setter and component references setters. Each setter has the name of property (event, component ref) and the value which is always an array. If all script control instances have the same value for the property then the value-array will have only one element, otherwise it is an array where each odd elements is a value and it’s next element is an index (or array of indexes) in html elements array.

Combining is controlled by ScriptManager’s property CombineScriptDescriptors.

A few steps and you can use it with AjaxControlToolkit:

  • Add reference to CombinedDescriptors.dll (or whatever dll you’ve put the classes in) to AjaxControlToolkit project

  • Derive ExtenderControlBase class (AjaxControlToolkit\ExtenderBase\ExtenderControlBase.cs) from my ExtenderControlBase class

  • Derive ScriptControlBase class (AjaxControlToolkit\ExtenderBase\ScriptControlBase .cs) from my ScriptControlBase class

  • Derive ToolkitScriptManager class (AjaxControlToolkit\ToolkitScriptManager\ToolkitScriptManager.cs) from my ToolkitScriptManager class

If you want to test it with AjaxControlToolkit SampleWebSite , change the web site’s trust level to Full (<system.web><trust level="Full"/>), add CombineScriptDescriptors=”true” to the declaration of the ajaxToolkit:ToolkitScriptManager in \App_Themes\SampleSiteTheme\ToolkitScriptManager.skinfile and add the code for $createMultiple function to Common.js in AjaxControlToolkit project.

As Reflection to private types and members is used it may not work in next versions of ASP.NET.

Now it works in .NET 3.5 and .NET 4 Beta 2.

CombinedScriptDescriptors.zip

четверг, 8 октября 2009 г.

HttpApplication.Init method

HttpApplication class has a method  Init. It is virtual and called by ASP.NET runtime when initializing of a HttpApplication is almost finished i.e. all modules have been initialized and all event handlers in the Global.asax have been registered. It is also lat time when you can attach handlers to the HttpApplication events. The method is quite handy if you want to place your custom HttpApplication in a separate  class library project.

I’ve used it to see which modules are registered for an application and subscribed for the application events,  and how much time each stage of the request processing takes. The output looks like the following.

See attached file

Modules HttpApplication event handlers Timing
OutputCache
Session
WindowsAuthentication
FormsAuthentication
PassportAuthentication
RoleManager
UrlAuthorization
FileAuthorization
AnonymousIdentification
Profile
ErrorHandlerModule
ServiceModel
DefaultAuthentication
BeginRequest
  ASP.global_asax.Application_BeginRequest

AuthenticateRequest
  System.Web.Security.WindowsAuthenticationModule.OnEnter
  System.Web.Security.PassportAuthenticationModule.OnEnter

DefaultAuthentication
  System.Web.Security.DefaultAuthenticationModule.OnEnter

PostAuthenticateRequest
  System.ServiceModel.Activation.HttpModule.ProcessRequest

AuthorizeRequest
  System.Web.Security.UrlAuthorizationModule.OnEnter
  System.Web.Security.FileAuthorizationModule.OnEnter

ResolveRequestCache
  System.Web.Caching.OutputCacheModule.OnEnter

AcquireRequestState
  System.Web.Profile.ProfileModule.OnEnter

AcquireRequestStateAsync 
   System.Web.SessionState.SessionStateModule.BeginAcquireState 
   System.Web.SessionState.SessionStateModule.EndAcquireState

ReleaseRequestState
  System.Web.SessionState.SessionStateModule.OnReleaseState

UpdateRequestCache
  System.Web.Caching.OutputCacheModule.OnLeave

EndRequest
  System.Web.SessionState.SessionStateModule.OnEndRequest
  System.Web.Security.PassportAuthenticationModule.OnLeave
  System.Web.Profile.ProfileModule.OnLeave
Stage From BeginRequest From Last Stage
ticks ms ticks ms
BeginRequest
AuthenticateRequest 13 .01 13 .01
DefaultAuthentication 20 .01 7
PostAuthenticateRequest 45 .02 25 .01
AuthorizeRequest 79 .04 34 .02
PostAuthorizeRequest 84 .04 5
ResolveRequestCache 91 .04 7
PostResolveRequestCache 96 .05 5
PostMapRequestHandler 179 .08 83 .04
AcquireRequestState 214 .1 35 .02
PostAcquireRequestState 220 .1 6
PreRequestHandlerExecute 225 .11 5
PostRequestHandlerExecute 309 .15 84 .04
ReleaseRequestState 318 .15 9
PostReleaseRequestState 323 .15 5
UpdateRequestCache 331 .16 8
PostUpdateRequestCache 336 .16 5
EndRequest 344 .16 8