Tải bản đầy đủ - 0 (trang)
Chapter 19.  Marshaling and Remoting

Chapter 19.  Marshaling and Remoting

Tải bản đầy đủ - 0trang

domains);theseinturnaredividedintovariouscontexts.App

domainsactlikelightweightprocesses,andcontextscreate

boundariesthatobjectswithsimilarrulescanbecontained

within.Attimes,objectswillbemarshaledacrossbothcontext

andappdomainboundaries,aswellasacrossprocessand

machineboundaries.

Whenanobjectismarshaledbyvalue,itappearstobesent

throughthewirefromonecomputertoanother,muchlike

CaptainKirkbeingteleporteddowntothesurfaceofaplanet

somemilesbelowtheorbitingUSSEnterprise.

InStarTrek,Kirkwasactuallysenttotheplanet,butinthe

.NETedition,itisallanillusion.Ifyouarestandingonthe

surfaceoftheplanet,youmightthinkyouareseeingand

talkingwiththerealKirk,butyouaren'ttalkingtoKirkatall:

youaretalkingtoaproxy,perhapsahologram,whosejobisto

takeyourmessageuptotheEnterprisewhereitisrelayedto

therealKirk.

BetweenyouandKirktherearealsoanumberof"sinks."Asink

isanobjectwhosejobistoenforcepolicy.Forexample,ifKirk

triestotellyousomethingthatmightinfluencethe

developmentofyourcivilization,theprime-directivesinkmight

disallowthetransmission.

WhentherealKirkresponds,hepasseshisresponsethrough

varioussinksuntilitgetstotheproxyandtheproxytellsyou.

ItseemstoyouasthoughKirkisreallythere,buthe'sactually

sneakingupbehindyoutothwartyournefariousplans.Alas,it

turnsoutthatitwasMr.Suluwhowascontrollingthehologram

thewholetime.Betterlucknextepisode.

Theactualtransmissionofyourmessageisdonebyachannel.

Thechannel'sjobistoknowhowtomovethemessagefrom

theEnterprisetotheplanet.Thechannelworkswitha

formatter.Theformattermakessurethemessageisintheright

format.PerhapsyouspeakonlyVulcan,andthepoorCaptain



doesn't.Theformattercantranslateyourmessageinto

FederationStandard,andtranslateKirk'sresponsefrom

FederationStandardbacktoVulcan.Youappeartobetalking

withoneanother,buttheformatter(knownastheuniversal

translatorintheStarTrekuniverse)issilentlyfacilitatingthe

communication.

Thischapterdemonstrateshowyourobjectscanbemarshaled

acrossvariousboundaries,andhowproxiesandstubscan

createtheillusionthatyourobjecthasbeensqueezedthrough

thenetworkcabletoamachineacrosstheofficeoraroundthe

world.Inaddition,thischapterexplainstheroleofformatters,

channels,andsinks,andhowtoapplytheseconceptstoyour

programming.



19.1.ApplicationDomains

Aprocessis,essentially,arunningapplication.Each.NET

applicationrunsinitsownprocess.IfyouhaveWord,Excel,

andVisualStudioopen,youhavethreeprocessesrunning.If

youopenOutlook,anotherprocessstartsup.Eachprocessis

subdividedintooneormoreapplicationdomains.Anapp

domainactslikeaprocessbutusesfewerresources.

Appdomainscanbeindependentlystartedandhalted.Theyare

secure,lightweight,andversatile.Anappdomaincanprovide

faulttolerance;ifyoustartanobjectinasecondappdomain

anditcrashes,itwillbringdowntheappdomainbutnotyour

entireprogram.Youcanimaginethatwebserversmightuse

appdomainsforrunningusers'code;ifthecodehasaproblem,

thewebservercanmaintainoperations.

AnappdomainisencapsulatedbyaninstanceoftheAppDomain

class,whichoffersanumberofmethodsandproperties.Afew

ofthemostimportantarelistedinTable19-1.

Table19-1.MethodsandpropertiesoftheAppDomainclass

Methodorproperty



Details



CurrentDomain



Publicstaticpropertythatreturnstheapplicationdomainforthe

currentthread



CreateDomain()



Overloadedpublicstaticmethodthatcreatesanewapplication

domain



GetCurrentThreadID() Publicstaticmethodthatreturnsthecurrentthreadidentifier

Unload()



Publicstaticmethodthatremovesthespecifiedappdomain



FriendlyName



Publicpropertythatreturnsthefriendlynameforthisapp

domain



DefineDynamicAssembly( Overloadedpublicmethodthatdefinesadynamicassemblyin

)

thecurrentappdomain

ExecuteAssembly()



Publicmethodthatexecutesthedesignatedassembly



GeTData()



Publicmethodthatgetsthevaluestoredinthecurrent

applicationdomaingivenakey



Load()



Publicmethodthatloadsanassemblyintothecurrentapp

domain



SetAppDomainPolicy()



Publicmethodthatsetsthesecuritypolicyforthecurrentapp

domain



SetData()



Publicmethodthatputsdataintothespecifiedappdomain

property



Appdomainsalsosupportavarietyofeventsincluding

AssemblyLoad,AssemblyResolve,ProcessExit,and

ResourceResolve--thatarefiredasassembliesarefound,

loaded,run,andunloaded.

Everyprocesshasaninitialappdomain,andcanhave

additionalappdomainsasyoucreatethem.Eachappdomain

existsinexactlyoneprocess.Untilnow,alltheprogramsinthis

bookhavebeeninasingleappdomain:thedefaultapp

domain.Eachprocesshasitsowndefaultappdomain.Inmany,

perhapsinmostoftheprogramsyouwrite,thedefaultapp

domainwillbeallthatyou'llneed.

However,therearetimeswhenasingledomainisinsufficient.

Youmightcreateasecondappdomainifyouneedtoruna

librarywrittenbyanotherprogrammer.Perhapsyoudon'ttrust

thelibrary,andwanttoisolateitinitsowndomainsothatifa

methodinthelibrarycrashestheprogram,onlytheisolated

domainwillbeaffected.IfyouweretheauthorofInternet



InformationServer(IIS),Microsoft'swebhostingsoftware),you

mightspinupanewappdomainforeachplug-inapplicationor

eachvirtualdirectoryyouhost.Thiswouldprovidefault

tolerancesothatifonewebapplicationcrashed,itwouldnot

bringdownthewebserver.

Itisalsopossiblethattheotherlibrarymightrequireadifferent

securityenvironment;creatingasecondappdomainallowsthe

twosecurityenvironmentstocoexist.Eachappdomainhasits

ownsecurity,andtheappdomainservesasasecurity

boundary.

Appdomainsaren'tthreadsandshouldbedistinguishedfrom

threads.AWin32threadexistsinoneappdomainatatime,

andathreadcanaccess(andreport)whichappdomainitis

executingin.Appdomainsareusedtoisolateapplications;

withinanappdomaintheremightbemultiplethreadsoperating

atanygivenmoment(seeChapter20).

Toseehowappdomainswork,let'ssetupanexample.

SupposeyouwishyourprogramtoinstantiateaShapeclass,

butinasecondappdomain.



ThereisnogoodreasonforthisShapeclasstobeputinasecondapp

domain,excepttoillustratehowthesetechniqueswork.Itispossible,

however,thatmorecomplexobjectsmightneedasecondappdomain

toprovideadifferentsecurityenvironment.Further,ifyouarecreating

classesthatmightengageinriskybehavior,youmightlikethe

protectionofstartingtheminasecondappdomain.



Normally,you'dloadtheShapeclassfromaseparateassembly,

buttokeepthisexamplesimple,you'lljustputthedefinitionof

theShapeclassintothesamesourcefileasalltheothercodein

thisexample(seeChapter17).Further,inaproduction

environment,youmightruntheShapeclassmethodsina



separatethread,butforsimplicity,you'llignorethreadingfor

now.(ThreadingiscoveredindetailinChapter20.)By

sidesteppingtheseancillaryissues,youcankeeptheexample

straightforwardandfocusonthedetailsofcreatingandusing

applicationdomainsandmarshalingobjectsacrossappdomain

boundaries.



19.1.1.CreatingandUsingAppDomains

Createanewappdomainbycallingthestaticmethod

CreateDomain()ontheAppDomainclass:

AppDomainad2=

AppDomain.CreateDomain("ShapeDomain");



ThiscreatesanewappdomainwiththefriendlynameShape

Domain.Thefriendlynameisaconveniencetotheprogrammer;

itisawaytointeractwiththedomainprogrammaticallywithout

knowingtheinternalrepresentationofthedomain.Youcan

checkthefriendlynameofthedomainyou'reworkinginwith

theproperty

System.AppDomain.CurrentDomain.FriendlyName.

OnceyouhaveinstantiatedanAppDomainobject,youcan

createinstancesofclasses,interfaces,andsoforth,usingits

CreateInstance()method.Here'sthesignature:

publicObjectHandleCreateInstance(

stringassemblyName,

stringtypeName,

boolignoreCase,

BindingFlagsbindingAttr,

Binderbinder,

object[]args,



CultureInfoculture,

object[]activationAttributes,

EvidencesecurityAttributes

);



Andhere'showtouseit:



ObjectHandleoh=ad2.CreateInstance(

"ProgCSharp",//theassembly

"ProgCSharp.Shape",//thetypenam

false,//ignorecase

System.Reflection.BindingFlags.CreateInstance,//flag

null,//binder

newobject[]{3,5},//args

null,//culture

null,//activationa

null);//securityatt



Thefirstparameter(ProgCSharp)isthenameoftheassembly,

andthesecond(ProgCSharp.Shape)isthenameoftheclass.

Theclassnamemustbefullyqualifiedbynamespaces.

Abinderisanobjectthatenablesdynamicbindingofan

assemblyatruntime.Itsjobistoallowyoutopassin

informationabouttheobjectyouwanttocreate,tocreatethat

objectforyou,andtobindyourreferencetothatobject.Inthe

vastmajorityofcases,includingthisexample,you'llusethe

defaultbinder,whichisaccomplishedbypassinginnull.

Itispossible,ofcourse,towriteyourownbinderthatmight,

forexample,checkyourIDagainstspecialpermissionsina

databaseandreroutethebindingtoadifferentobject,basedon

youridentityoryourprivileges.



Bindingtypicallyreferstoattachinganobjectnametoanobject.

Dynamicbindingreferstotheabilitytomakethatattachmentwhenthe

programisrunning,asopposedtowhenitiscompiled.Inthisexample,

theShapeobjectisboundtotheinstancevariableatruntime,through

theappdomain'sCreateInstance()method.



Bindingflagshelpthebinderfine-tuneitsbehavioratbinding

time.Inthisexample,usetheBindingFlagsenumerationvalue

CreateInstance.Thedefaultbindernormallylooksatpublic

classesonlyforbinding,butyoucanaddflagstohaveitlookat

privateclassesifyouhavetherightpermissions.

Whenyoubindanassemblyatruntime,don'tspecifythe

assemblytoloadatcompiletime;rather,determinewhich

assemblyyouwantprogrammatically,andbindyourvariableto

thatassemblywhentheprogramisrunning.

Theconstructoryou'recallingtakestwointegers,whichmust

beputintoanobjectarray(newobject[]{3,5}).Youcansend

nullfortheculturebecauseyou'llusethedefault(en)culture

andwon'tspecifyactivationattributesorsecurityattributes.

Yougetbackanobjecthandle,whichisatypethatisusedto

passanobject(inawrappedstate)betweenmultipleapp

domainswithoutloadingthemetadataforthewrappedobjectin

eachobjectthroughwhichtheObjectHandleTRavels.Youcan

gettheactualobjectitselfbycallingUnwrap()ontheobject

handle,andcastingtheresultingobjecttotheactualtypeinthis

case,Shape.

TheCreateInstance()methodprovidesanopportunityto

createtheobjectinanewappdomain.Ifyouweretocreate

theobjectwithnew,itwouldbecreatedinthecurrentapp

domain.



19.1.2.MarshalingAcrossAppDomain

Boundaries

You'vecreatedaShapeobjectintheShapedomain,butyou're

accessingitthroughaShapeobjectintheoriginaldomain.To

accesstheshapeobjectinanotherdomain,youmustmarshal

theobjectacrossthedomainboundary.

Marshalingistheprocessofpreparinganobjecttomoveacross

aboundary;onceagain,likeCaptainKirktransportingtothe

planet'ssurface.Marshalingisaccomplishedintwoways:by

valueorbyreference.Whenanobjectismarshaledbyvalue,a

copyismade.ItisasifIcalledyouonthephoneandasked

youtosendmeyourcalculator,andyoucalleduptheoffice

supplystoreandhadthemsendmeonethatisidenticalto

yours.IcanusethecopyjustasIwouldtheoriginal,but

enteringnumbersonmycopyhasnoeffectonyouroriginal.

Marshalingbyreferenceisalmostlikesendingmeyourown

calculator.Here'showitworks.Youdon'tactuallygivemethe

original,butinsteadkeepitinyourhouse.Youdosendmea

proxy.Theproxyisverysmart:whenIpressabuttononmy

proxycalculator,itsendsasignaltoyouroriginalcalculator,and

thenumberappearsoverthere.Pressingbuttonsontheproxy

looksandfeelstomejustlikeItouchedyouroriginalcalculator.



19.1.2.1Understandingmarshalingwithproxies

TheCaptainKirkandcalculatoranalogiesarefineasfaras

analogiesgo,butwhatactuallyhappenswhenyoumarshalby

reference?TheCLRprovidesyourcallingobjectwitha

transparentproxy(TP).

ThejoboftheTPistotakeeverythingknownaboutyour

methodcall(thereturnvalue,theparameters,etc.)offofthe



stackandstuffitintoanobjectthatimplementstheIMessage

interface.ThatIMessageispassedtoaRealProxyobject.

RealProxyisanabstractbaseclassfromwhichallproxies

derive.Youcanimplementyourownrealproxy,oranyofthe

otherobjectsinthisprocessexceptforthetransparentproxy.

ThedefaultrealproxywillhandtheIMessagetoaseriesofsink

objects.

Anynumberofsinkscanbeuseddependingonthenumberof

policiesyouwishtoenforce,butthelastsinkinachainwillput

theIMessageintoachannel.Channelsaresplitintoclient-side

andserver-sidechannels,andtheirjobistomovethemessage

acrosstheboundary.Channelsareresponsiblefor

understandingthetransportprotocol.Theactualformatofa

messageasitmovesacrosstheboundaryismanagedbya

formatter.The.NETFrameworkprovidestwoformatters:a

SOAPformatter,whichisthedefaultforHTTPchannels,anda

Binaryformatter,whichisthedefaultforTCP/IPchannels.You

arefreetocreateyourownformattersand,ifyouaretrulya

gluttonforpunishment,yourownchannels.

Onceamessageispassedacrossaboundary,itisreceivedby

theserver-sidechannelandformatter,whichreconstitutethe

IMessageandpassittooneormoresinksontheserverside.

ThefinalsinkinasinkchainistheStackBuilder,whosejobis

totaketheIMessageandturnitbackintoastackframesothat

itappearstobeafunctioncalltotheserver.



19.1.2.2Specifyingthemarshalingmethod

Toillustratethedistinctionbetweenmarshalingbyvalueand

marshalingbyreference,inthenextexampleyou'lltellthe

Shapeobjecttomarshalbyreferencebutgiveitamember

variableoftypePoint,whichyou'llspecifyasamarshalby

value.



Notethateachtimeyoucreateaclassthatmightbeused

acrossaboundary,youmustchoosehowitwillbemarshaled.

Normally,objectscan'tbemarshaledatall;youmusttake

actiontoindicatethatanobjectcanbemarshaled,eitherby

valueorbyreference.

Theeasiestwaytomakeanobjectmarshalbyvalueistomark

itwiththeSerializableattribute:

[Serializable]

publicclassPoint



Whenanobjectisserialized,itsinternalstateiswrittenouttoa

stream,eitherformarshalingorforstorage.Thedetailsof

serializationarecoveredinChapter21.

Theeasiestwaytomakeanobjectmarshalbyreferenceisto

deriveitsclassfromMarshalByRefObject:

publicclassShape:MarshalByRefObject



TheShapeclasswillhavejustonemembervariable,upperLeft.

ThisvariablewillbeaPointobject,whichholdsthecoordinates

oftheupper-leftcorneroftheshape.

TheconstructorforShapewillinitializeitsPointmember:

publicShape(intupperLeftX,intupperLeftY)

{

Console.WriteLine("[{0}]Event{1}",

System.AppDomain.CurrentDomain.FriendlyName,

"Shapeconstructor");

upperLeft=newPoint(upperLeftX,upperLeftY);

}



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 19.  Marshaling and Remoting

Tải bản đầy đủ ngay(0 tr)

×