c#揭密ii(大师们在说些什么?)
先声明这篇文章属于收藏性质的,推荐给那些喜欢dotnet技术的爱好者。
这之前我曾转载了o'reilly的一篇关于c#的访谈录。o'reilly一向以技术和评论公见长,他们的编辑一般都有着很深的技术背景和功力(所以出的书也比较贵haha),所以那篇着重整个流行技术,有不少是和java相关的;而这一篇都是ms内部的几个高手在交谈聊天,涉及的范围比上次的专访要广,里面有一些很新奇的术语和许多问题的观点。另外我认为这篇文章对以前非常熟悉com+、asp和window dna(n 层结构)的人目前评估和思考向新的dotnet体系迁移都很有帮助。
anders hejlsberg是个很奇怪的人,从他身上你感觉不到一个程序语言创始人那种对某种语言偏爱的狂热,却很容易感觉到他所透露出的那种对技术对程序语言的坚定和深厚理解。很喜欢他在上一篇访谈录中说的一句话:“language is a funny thing: it's a matter of taste. language is almost a religious thing, and it's a lifestyle choice for programmers。”不过我知道这句话说的不是他自己。这篇文章中还有好些人:brian harry,peter golde ,scott guthrie(asp老怪),mark anders。有了这些人,microsoft有福啊。
小气的神
2001.09.24
--------------------------------------------------------------------------------
conversations on .net
derived from on-line chats with our early adopters, a series of conversations with microsoft engineers, designers, and developers look at issues involving c#, asp.net, and the common language runtime.
http://msdn.microsoft.com/library/default.asp?url=/library/techart/dotnetconvers.htm
summary: what follows is a series of conversations with microsoft engineers, designers, and developers, looking at issues involving c#, asp.net, and the common language runtime. (10 printed pages)
a conversation with anders hejlsberg and peter golde on c#
anders hejlsberg is a distinguished engineer in the developer division at microsoft corporation. he is the chief designer of the c# programming language and a key participant in the development of the .net framework. previously, anders was the architect for visual j++ and the windows foundation classes.
peter golde is a software design engineer in the developer division at microsoft corporation. peter has worked on development tools at microsoft for over 10 years, contributing to products such as microsoft c, ole automation, visual basic, visual basic for applications, and visual j++.
q: peter, you attended the ecma meetings in march. can you disclose anything about what's going on there that is new?
peter golde: sure. as some of you may know, microsoft, intel, and hp jointly submitted two specifications to ecma for standardization via the ecma process. these two specifications are the c# language and the common language infrastructure (cli), which is a subset of the .net framework. we're meeting with a number of companies every month as part of the standardization process. it's difficult to predict the schedule with absolute certainty, but we hope that ecma will be able to complete standards for both parts by the end of 2001.
q: how does the cli compare to the cls and the cts?
anders hejlsberg: cls stands for common language specification, cts stands for common type system. the cls is a specification of what features any programming language implemented on the .net platform must support.
q: ok, the cls is less than the cts. where does the cli fit?
anders hejlsberg: the cts is basically another word for the type system in .net, i.e. a specification of what a class, struct, enum, or such is. cli is really just another word for the large subset of the .net framework that we submitted to ecma.
peter golde: the cli includes the cls and the cts.
q: anders, after your work on turbo pascal, delphi, visual j++ and now c#, how do you see programming languages evolving today?
anders hejlsberg: jeeez, had to ask an easy one, eh? i guess i'm becoming less and less of a believer in revolutionary approaches to language design. it really is amazing how much the capabilities of computing have evolved, yet we're basically still using the same kinds of programming languages. it gives me hope that we can go even further with an evolutionary approach where we don't just invalidate all the work that went before.
q: have you thought much about moving toward an intentional programming model?
anders hejlsberg: can't say that we have. as i see it, one of the problems of intentional programming is that you're basically creating a new programming language for every domain specific application. i really am more of a believer in having a core set of abstractions (such as classes, methods, properties, and events) and then applying them in each domain—but in a way that preserves familiarity.
q: customers looking at the .net framework for their application development efforts have asked whether or not the common language runtime (clr) is a virtual machine (vm), and if so, what limitations or penalties associated with vms (performance and so forth) will folks need to consider in their efforts?
peter golde: yes, i think that the clr can be considered in the broad class of things that one might call a vm. as to performance, though, i don't think that this classification says much of anything interesting about performance. you should judge performance by measuring performance on the applications that you are interested in. don't try to prejudge performance based on your preconceptions about what will and won't be slow—just test it!
q: peter, are there any kind of applications that you would explicitly not build on the clr due to issues with running managed versus unmanaged code?
peter golde: in terms of what applications i wouldn't write, i would say that "hard real-time" kinds of programs probably wouldn't be a good fit (at least right now), because we don't make very strong guarantees about the garbage collector, things like robot control and the like. there are real-time friendly garbage collection algorithms, so i don't think this would be a limitation forever.
q: can you discuss any advantages c# would have over visual basic (vb) in terms of the framework?
anders hejlsberg: regarding c# vs. visual basic, it really primarily comes down to what you already know and are comfortable with. it used to be that there was a large perf difference between vb and c++, but since c# and vb.net use the same execution engine, you really should expect the same perf. c# may have a few more "power" features (such as unsafe code), and vb.net may be skewed a bit more towards ease of use (e.g. late bound methods calls), but the differences are very small compared to what they were in the past.
q: ok, can you contrast c# with vb.net? questions usually come in the form of "i know you guys say vb.net and c# let you do the same thing, but c# was designed for the clr, so i don't believe you when you say vb.net is just as good."
anders hejlsberg: regarding c# versus vb.net, the reality is that programmers typically have experience with either c++ or vb, and that makes either c# or vb.net a natural choice for them. the already existing experience of a programmer far outweighs the small differences between the two languages.
q: it has been said a few times that c# is the language designed for the clr. considering that all the languages that microsoft will ship with the vs.net will be able to target all the features of the clr, what makes c# more clr "friendly" than the other?
peter golde: i don't think that c# is necessarily any more friendly to the clr than other languages. the clr has been designed to be accessible via multiple languages. however, you will probably find that c# is more strongly focused on the clr than other languages like c++, which have a number of other facilities that are less oriented toward the clr. by designing c# in conjunction with the clr, we have the "luxury" of not having backwards compatibility constraints.
q: is there any difference between the default equals function (implemented in object) and the =?
anders hejlsberg: for two reference types (classes), the default equals() method is the same as ==. but for value types (structs), there is no == operator unless you provide an implementation in the value type.
q: is lock (this) similar to the synchronize key word in java?
peter golde: yes, lock (<expression>) is extremely similar to synchronized (<expression>) in java. we don't support the notion of a modifier on methods, because our experience is that it leads to deadlock or poor performance in too many cases.
q: we mostly want the com+ benefits of memory caching, independent process space, etc.; we don't need to worry about database transactions. is this a valid reason to place clr components into com+, or is it better to just let the clr handle it?
anders hejlsberg: i would look at .net application domains and not use com+ in that case.
q: can you elaborate on .net application domains?
anders hejlsberg: sure. an application domain is sort of like a light-weight process. two application domains will share the same gc heap, but the clr provides automatic and transparent marshalling between the application domains. it allows you to protect light-weight processes from each other without taking the fairly large overhead of an os process.
q: is the application domain a similar concept to the java package?
anders hejlsberg: no, a java package is a different thing. the closest analogy in .net is an assembly.
q: what are the plans to allow c# code to run on a pocketpc?
peter golde: we've announced that we'll have a ".net compact framework" that will be optimized for portable devices. obviously there are limitations in terms of the scope of the class library, memory limitations, and so forth compared to the desktop or server. i should add that one of the focuses of the ecma standardization work is to standardize a library framework that is appropriate in size and scale for portable devices. there is obviously a large amount of interest in this from many companies.
a conversation with mark anders and scott guthrie on asp.net
scott guthrie co-founded the asp.net team and leads the design team responsible for architecting the product. his individual technical contributions include: asp.net web forms page architecture, asp.net web services infrastructure, asp.net compilation system, asp.net distributed session state infrastructure, asp+ deployment architecture, asp.net reliability system, and the asp.net http runtime architecture. prior to asp.net, scott was a member of the iis and windows nt teams.
as the microsoft product unit manager of the .net framework, mark anders leads the team that designs and develops the .net framework, including asp.net, windows forms, base class libraries, and other class libraries. prior to this, he co-founded the asp.net team and held lead positions in program management as well as development.
q: scott, mark, if you had to pick one thing, what do you think is the single coolest developer feature of asp.net?
mark anders: well, i'll tell you the feature that gets the most applause: it's tracing! seriously, it's almost a spontaneous standing ovation. one guy who i showed it to said that it was "the coolest thing i've ever seen." (note, i wouldn't go that far!) actually, my favorite feature is server controls.
scott guthrie: i think the partial page output caching feature that we are going to ship in beta2 is probably the coolest developer feature, because it can dramatically impact the performance of literally any site. the xcopy deployment features (no restart on dll updates) we have i think also are pretty close.
q: tracing is a great feature. one of the questions we get a lot: is there any penalty for having all the tracing code but turning it off when going into production?
scott guthrie: there shouldn't be any noticeable performance difference when tracing is turned off (but code left in). one thing to keep in mind, though, is that if you have expensive "trace calculations" that you output as part of tracing, then you should scope it within an "if (trace.enabled = true) then" block. when tracing is turned off, "trace.enabled" will return false
mark anders: note that we don't gather all of the statistics if trace==false.
q: could you discuss the security of the config files. i have seen a lot of concern that since they are simple xml files, they can be hacked into easily.
scott guthrie: we do block all access to the config files from remote users. however, i think the concern people have is whether a rogue user who gets access to the config file can modify and take over things. note that this problem exists with asp today as well, in that the metabase apis can be written to, which would effectively do the same thing. however, there are some things that you can do to reduce this problem. specifically, with asp.net we support the ability to "lock down" settings at a parent directory. for example, you might want to lock down the security identity of the worker process (i.e.: the username it runs under) at the machine level and then restrict sub-applications' abilities to override it.
q: i see confusion as to whether to mimic the windows dna model by creating asp presentation interfaces talking to com+ components, or in the .net era to just write code behind and stick dynamic link libraries (dlls) in the /bin and be done with it.
mark anders: i would say that services provided by com+ are still required if you want transactions. however, the model of using dcom to put components on another box and scale out that way is not recommended.
scott guthrie: in general i would recommend continuing to logically partition your application code (which was one of the things windows dna suggested). for example, putting all of your data access logic within modular classes that you then call them from pages—like we do from the ibuyspy applications. ...in general, you shouldn't use com+ transactions unless you are actually doing distributed transactions across multiple data store machines. if you are just updating a single database, then leverage the transaction capabilities within it.
q: what if you are planning on using remoting to communicate between our first and middle tiers, and you've only gotten c# working? are there any known issues today with using remoting to communicate from asp to visual basic (vb)?
scott guthrie: there shouldn't be any problems doing remoting from vb (like c#), although you should be a little careful about how to use remoting. in many cases it is best not to do the extra network hop. there is a big performance penalty to going to the other machine, so you shouldn't look to do it for either performance or scalability reasons. it does make sense if you are connecting to a different application or data center, where for org/technical or political reasons you need code to run elsewhere.
q: what if you want to use it to communicate from web servers that are hosted at an outsourcer across a firewall back to the network where the databases are? for security reasons, we won't put the database out in the dmz.
scott guthrie: one other possible solution you might also investigate for that would be to leverage isa (internet security and acceleration) server, where you would put isa in front of the firewall, and then asp.net and the database behind it. we actually just finished doing some benchmarking numbers with that solution and saw really great results. it is also really easy to set up and administer, and might be easier to ultimately deploy and manage going forward. one nice thing about isa is that it doesn't require any asp.net code changes to leverage it, so it is pretty easy to try out and evaluate.
q: could you comment on interoperability (via session objects, query strings, etc.) between asp and asp.net? any gotchas?
mark anders: there are a few. first, we've made the object models as close as possible. however, if for example you store com objects (not new clr objects) in sessions, and you want those to be out of proc, they won't work. you need to have new objects that can be serialized. one thing to note is that asp and asp.net will run side by side on a box, because at an application level asp and asp.net do not share sessions.
q: i've seen a lot of concern that data can be passed page to page (asp to and from asp.net).
mark anders: since we really use standard web techniques, passing info page to page should not be a problem. however, page to page in asp and asp.net typically assumes services that are provided by each, such as session and application state. these services are not shared, and so you can't rely on them.
scott guthrie: i have a list of things you can do to ease migration of asp code to asp.net.
1. use only a single language within the asp application. don't intermix vbscript and jscript together in the same page (in general a bad programming practice with asp, but also a migration issue for asp.net in that we now require only one inline <% %> language.
2. explicitly declare all of asp page functions within a <script language="vbscript" runat=server> block as opposed to <% %> blocks. in asp.net we no longer support this later function declaration option. it is just a copy/paste change in order to fix i
3. explicitly use vbscript's "option explicit" keyword at the top of every asp page (this will become the default with asp.net and will also ensure that you write slightly better code today).
4. use the "call" keyword anytime they call a subroutine in vbscript today (for example: "call foobar (1, 2)"). this will enable/require them to wrap parenthesis around all subroutine arguments (if you don't use the "call" keyword, then vbscript today will raise a compilation error if you have parentheses). in vb.net, parentheses are now required (note that the "call" keyword is still supported in vb.net). so if they didn't use the "call" keyword, they'd have to go back and change all subroutines.
5. avoid relying on "default properties" in vbscript, and instead fully qualify property references: (for example, with an ado recordset write: rs("a_name").value instead of just rs("a_name")). default properties are no longer supported in vb.net.
6. avoid using "render function" tricks (a specific unintended hack/trick that people can use in asp but which was never intended as a feature). instead explicitly use response. write blocks when constructing render functions.
q: scott, are there any estimates on the time needed to migrate a project from asp to asp.net? i've seen a rough number of 5 percent of the development time to migrate a vb 6 project to vb.net.
scott guthrie: i actually don't have any good time estimates. it's going to depend somewhat. in general, if you follow the asp coding suggestion i posted above, then i think the porting effort should be pretty minimal (a day or two for even complex apps)
a conversation with brian harry on the common language runtime
brian harry is the product unit manager for the common language runtime. he has contributed to the design and features of the clr from its very beginning, serving first as development manager and then as product unit manager. before the common language runtime, brian worked on sourcesafe and the microsoft repository. he joined microsoft in 1994.
q: we have heard a lot about possible support for generics in future versions of the runtime. can you explain your current thinking about generics, and how they might be used i.e. functional languages, templates etc.?
brian harry: we have had an effort in microsoft research for over a year to design and implement generics in the runtime. the research team has, in fact, already implemented generics in both the runtime and the c# compiler. the product team has reviewed the design and implementation and is generally happy with the approach. it is similar to the implementation we have for arrays. you'll note that arrays are a form of generic (or parameterized type).
q: is the clr for nt4 and windows 2000 a fully self-contained module for deployment purposes? in other words, does it upgrade iis on nt4 and supply all the elements needed as a fully self-contained entity?
brian harry: no, the clr does not redistribute many other pieces of the operating system. we will have a set of pre-requirements that will specify the os service pack, version of ie, etc. there will be a .net framework redistributable that is pared down from the sdk by quite a bit.
q: what is the relationship between the clr and the cli that's been submitted to the w3c?
brian harry: the cli is a specification for many of the core designs that the clr implements. in addition to the cli specification, the clr implements many windows specific features like com interop, windows security policy, windows forms, etc.
q: where are we in the ecma process?
brian harry: we are working with the technical committees to refine the specifications for submittal. this is a fairly long process and involves a lot of input and consensus building.
q: please explain how long and short weak references work and the usage scenarios for both.
brian harry: the differences between long and short weak references are when the object reference inside the weak reference gets nulled out.
q: so if the reference is held after gc then it is considered long?
brian harry: for short references, the contained reference gets nulled out as soon as the object is deemed unreachable. this is ultimately more performant because we remove the reference sooner. long weak references are nulled after the object has been finalized.
q: what benchmarks have been run comparing the clr to native code?
brian harry: we have run a large set of benchmarks comparing the clr to native code and are still measuring and tuning performance. we have broken benchmarks down into a variety of categories, including: web, rich windows apps, benchmarks and micro benchmarks. for web we have compared mostly to asp and a bit to jsp. asp.net proves to be substantially faster than both in almost every scenario. for rich windows apps we have taken a variety of forms-based apps and have focused on tuning working set and startup time. we have also done a variety of benchmarks like spec 95, spec 2000, bytemark, etc.
q: there have been a lot of questions about running transactions on the .net platform. care to comment?
brian harry: we fully support transactions on the .net platform. we fully support the com+ services and have worked hard to make sure that writing clr components is the best way possible to write software that takes advantage of the com+ services.
q: is there a lot of sample code for leveraging transactions from within .net code?
brian harry: indeed, there are quite a lot of samples of using all of the com+ services available. some are in the sdk and some are on gotdotnet.com
q: if i utilize com+ on windows 2000, will the clr enable com+ like functionality on nt4 or will some sort of mts interop have to occur?
brian harry: we have not done anything to move com+ services to nt4. mts is on nt4 and there have not been any recent updates to that code.
q: tell me about deployment of the clr and whistler—will it be native (in the shrink-wrap)?
brian harry: we have been looking at the schedules to decide whether the .net framework could ship with whistler. no decision has been made, so i have nothing to announce.
q: i am interested in your opinion of distributed transactions (two phase commit) over web services?
brian harry: my opinion is that you should not, in general be doing dtc style 2 phase commit across web services. i am not the expert on this, but web services were designed for loosely coupled computing and compensating transactions is a better approach to this style of application. that said, it is possible to build a tightly coupled app over web services, it just wasn't the design point.
q: so if you need to span a transaction across two web services calls, use a compensating transaction on failure?
brian harry: yes, that is my opinion, i'd be interested in what the com+ services team has to say about that, but i believe they would agree with me.
q: idempotent transactions then?
brian harry: i'm not sure what you mean by idempotent transaction. what i mean is a transaction that can be reversed.
q: can you talk about features of the clr that help high volume applications run faster and more stable than our existing platforms? for example, memory allocation appears to be rather streamlined now that gc is in the picture.
brian harry: there are several aspects to the .net framework that help improve reliability and scalability. starting with things like the built in thread pool, easy asynchronous programming, the general approach of a stateless server programming model that enables scale out, the asp.net process model that enables process recycling, auto restart, etc.
q: i know that was a pretty generic question. can you talk a little bit more about the built-in thread pool?
brian harry: the clr has a thread pool that has been heavily optimized to cooperate with the gc and the managed environment. it has a very simple and approachable api but is very powerful. further we are strongly promoting using the thread pool, especially in server apps rather than spinning up application threads to process work loads. using the thread pool will result in a much more scalable application
q: what exactly do you mean by "easy asynchronous programming."
brian harry: easy asynchronous programming. i mean, there is a well-established design pattern, our frameworks expose it where appropriate, we enable many modes: callback, polling, subsequent block for completion, etc. also, you can use asynchronous delegates to easily turn any api into an asynchronous api.
q: how is interoperability testing going with the clr being installed onto a system with many other apps already installed—office, visio, etc.?
brian harry: at a lower level type safe code helps reduce memory leaks, eliminates dangling pointers and deployment issues, all helping contribute to more reliable applications. we are thoroughly testing internally in every configuration we can imagine. further, we are doing a very wide beta program. recent data i saw showed that the .net framework beta1 had reached almost 1 million people.
q: what are the definite "no-no's" for developers writing to the clr?
brian harry: hmmm, most of the no-no's are the same as always—don't allocate too much memory, don't write n^2 algorithms, etc. the main things that are added, are you need to be careful where your managed/unmanaged boundaries are and how many times you cross them. you also need to be aware of security checks. too many can kill your perf so you need to design for them.
q: can you comment on the clr on other non-windows platforms?
brian harry: we have a product under development called the .net compact framework targeted at devices and designed to be very portable. we also have submitted the core specs to ecma and expect to get a lot of cross platform implementations as a result of that.
q: are there design considerations for those writing applications to the clr to make it easy to run on starlite? i'm thinking architecture of the applications to make it easy to have a clr version and a read-made starlite version? "ready-made" type.
brian harry: yes, the .net compact framework will have a subset of the overall .net class libraries (in order to keep the size down) but it will also include device specific features (like wireless apis). you can either write an app that targets .net compact framework, leveraging the device apis, or you can write one that targets the intersection with the desktop. i believe the docs will help you identify this intersection.
q: in reference to string manipulation, it appears that we can no longer directly manipulate the buffer in managed code. for example, string[0] = 'a'. instead we do something like string.replace(0, 'a') and get a new string back.
brian harry: yes, the reason for this is that strings are immutable. this makes for a simpler programming model and eliminates problems around synchronization and sharing of strings. in some cases, it allows us to give better performance by avoiding copying strings.
stringbuilder allows you to modify the string in place. a string builder can be converted to a string and then it becomes immutable.
q: does this mean if i had a member variable that is a streamreader, i will need to implement it to be able to call the streamreader's close method?
brian harry: streamreader—it will depend on how your class is used, but if you are exposing it out to arbitrary clients, then yes you might want to.
q: under what conditions do i need to implement idisposable.
brian harry: a class should implement idisposable if it encapsulates "limited" resources. examples are: window handles, file handles, database connections, etc. anything where the user of the resource needs to be able to free itpreemptively.
q: a related question is why do you really care about resurrection, i.e. getting the object back to life once it has died?
brian harry: actually, i don't care about resurrection; it is a terrible thing in my opinion. it is somewhat of a necessary evil of the notion of finalizers. we had a plan (which we may bring back in a future version) for something called "static finalizers" that would eliminate the possibility of resurrection.
q: is it true that deterministic finalization cannot be achieved because of resurrection, or am i mixing them here?
brian harry: no, deterministic finalization has nothing to do with resurrection. resurrection is an issue after we have already run the finalizer. deterministic finalization (as i have most frequently heard it used) has to do with not calling the finalizer at a well-defined point in time.
q: which brings us back to my question about when to use long and short weak references?
brian harry: long/short—as a general rule, always use short weak references. only use long ones if you need to access the handle to find the object even during finalization. this is a very rare need. there are some caching schemes where this turns out to be valuable but i don't think i could describe them very well without spending a while to think about it.