Search Results

Search found 10851 results on 435 pages for 'state diagram'.

Page 9/435 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • c# how to set up and use session state from preinit

    - by Praesagus
    OK so to set and read variables from the current session String Myvar =(string) System.Web.HttpContext.Current.Session[“MyVariable”] To set System.Web.HttpContext.Current.Session[“MyVariable”] = “NewValue” I can do neither, I get a System.NullReferenceException: Object reference not set to an instance of an object. from System.Web.HttpContext.Current.Session. In my web.config I have <sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:42424" cookieless="false" timeout="20"> </sessionState> I have read a dozen articles on the the necessity of IHttpHandler and an IRequiresSessionState interface. I think the issue may be caused because I am requesting this information in Page_PreInit. I found a solution in a stack overflow article but I don't seem be using it properly to actually make this go. I am not sure what I am missing. Thanks in advance.

    Read the article

  • Codeigniter: State Machine how to

    - by Kevin Brown
    I created a db row called "activity_state" to denote which things a user has and hasn't completed. The problem is, I don't know how to use it... How can I use this single row to determine what a user has done? ie. have they completed their profile?, have they completed an assignment? Someone mentioned using it as a bitfield, but I'm unfamiliar with that. Is that a good idea? Any ideas?

    Read the article

  • Session state has been disabled for ASP.NET.The Report Viewer control requires that session state be

    - by Patrick Olurotimi Ige
    While i was trying to setup some reports on a SPF 2010 site. After trying to add a Sql Reporting Webpart i get the error: Session state has been disabled for ASP.NET. The Report Viewer control requires that session state be enabled in local mode I never came across that error before when using RSWebaprts in Sharepoint 2007:) But i think is related to ASP.NET sessions state:( Any to fix it you would have to start to make sure the SharePoint Server ASP.NET Session State Service is enabled. Unfortunately in Sharepiint SPF2010 and SP 2010 you would have to do it using PowerShell By doing :  Enable-SPSessionStateService -Defaultprovision PS C:\> PSSnapin - Shows you all the PS Snapins PS C:\> Add-PSSnapin "Microsoft.SharePoint.PowerShell" -- Adds the Sharepoint PS Snapin PS C:\> get-command -Noun SP* -- Show all SP cmdlets PS C:\> Add-SPShellAdmin -- (If you get error regarding the access to the farm you use this command to add an acct to able to run the Shell admin) PS C:\> Get-Help Enable-SPSessionStateService - Shows helpp for  Enable-SPSessionStateService PS C:\> Enable-SPSessionStateService -Defaultprovision - (enables/activates SPSessionStateService) you have more oprions available when you run the Get-Help Enable-SPSessionStateService   After running the cmd you should see the SharePoint Server ASP.NET Session State Service started in your service applications in the Central Admin Site. And of course be able to add your RS webparts Enjoy

    Read the article

  • 6 Things You Shouldn’t Do With Solid-State Drives

    - by Chris Hoffman
    Solid-state drives are different from the mechanical, magnetic hard drives in wide use. Many of the things you’ve done with typical mechanical hard drives shouldn’t be done with newer solid-state drives. Solid-state drives are presented by the operating system the same way mechanical drives are, but they work differently. If you’re a geek, knowing what you shouldn’t do is important.    

    Read the article

  • Idle state detection for server

    - by odinmillion
    Windows OS has a service that detects idle state. Details: Task Idle Conditions The computer is considered idle if all the processors and all the disks were idle for more than 90% of the past 15 minutes and if there is no keyboard or mouse input during this period of time. When the Task Scheduler service detects that the computer is idle, the service only waits for user input to mark the end of the idle state. It is very useful for usual PCs that have keyboard amd mouse. We can use standard task scheduler to start some process like defrag when PC in idle state and stop when PC isn't in idle state. But what should we use when we using a standalone server without keyboard and mouse? Server sometimes receives commands by TCP/IP and starts CPU and HDD activity. But sometimes CPU and HDD activity at zero level. I would like to use this periods of time to start defrag or another process. But this started at "idle" state processes should be terminated when another commands will appear. So, standard idle state conditions cant help me because we have not got user input to stop idle state. I need more customizable idle state detector. Automatically started processes shouldn't influence to idle state, but PC should go away from idle state when another process will apperar. What should I use? Maybe exists some advansed task scheduler? Or I should write some useful utility on C#? I hope that it is a standard task and all useful utilities already compiled :)

    Read the article

  • How to Easily Reset a Computer Back to a Clean State Each Time It Boots

    - by Chris Hoffman
    When you’re managing a public computer, you need a special kind of tool. You need a way to reset that computer back to a clean state every time it boots so no one can make any harmful changes. Commercial solutions like Deep Freeze offer this feature, and Microsoft once offered it via its Windows Steady State tool for Windows XP and Vista. However, Windows Steady State has been discontinued and doesn’t work with Windows 7. We’ll be using Reboot Restore Rx for this, as it supports both Windows 7 and Windows 8. Steadier State is another solid option, but it only works in Windows 7, and even then only with Windows 7 Enterprise and Ultimate.    

    Read the article

  • Issues with touch buttons in XNA (Release state to be precise)

    - by Aditya
    I am trying to make touch buttons in WP8 with all the states (Pressed, Released, Moved), but the TouchLocationState.Released is not working. Here's my code: Class variables: bool touching = false; int touchID; Button tempButton; Button is a separate class with a method to switch states when touched. The Update method contains the following code: TouchCollection touchCollection = TouchPanel.GetState(); if (!touching && touchCollection.Count > 0) { touching = true; foreach (TouchLocation location in touchCollection) { for (int i = 0; i < menuButtons.Count; i++) { touchID = location.Id; // store the ID of current touch Point touchLocation = new Point((int)location.Position.X, (int)location.Position.Y); // create a point Button button = menuButtons[i]; if (GetMenuEntryHitBounds(button).Contains(touchLocation)) // a method which returns a rectangle. { button.SwitchState(true); // change the button state tempButton = button; // store the pressed button for accessing later } } } } else if (touchCollection.Count == 0) // clears the state of all buttons if no touch is detected { touching = false; for (int i = 0; i < menuButtons.Count; i++) { Button button = menuButtons[i]; button.SwitchState(false); } } menuButtons is a list of buttons on the menu. A separate loop (within the Update method) after the touched variable is true if (touching) { TouchLocation location; TouchLocation prevLocation; if (touchCollection.FindById(touchID, out location)) { if (location.TryGetPreviousLocation(out prevLocation)) { Point point = new Point((int)location.Position.X, (int)location.Position.Y); if (prevLocation.State == TouchLocationState.Pressed && location.State == TouchLocationState.Released) { if (GetMenuEntryHitBounds(tempButton).Contains(point)) // Execute the button action. I removed the excess } } } } The code for switching the button state is working fine but the code where I want to trigger the action is not. location.State == TouchLocationState.Released mostly ends up being false. (Even after I release the touch, it has a value of TouchLocationState.Moved) And what is more irritating is that it sometimes works! I am really confused and stuck for days now. Is this the right way? If yes then where am I going wrong? Or is there some other more effective way to do this? PS: I also posted this question on stack overflow then realized this question is more appropriate in gamedev. Sorry if it counts as being redundant.

    Read the article

  • how to save and load the state of a game in scheme

    - by user3667664
    I'm creating the game of chess in scheme, but do not know how to save and load game state is a part I have this code (define-struct ficha(color se-movio? tipo-ficha )) ;;tablero lista de listas de fichas (define-struct estado (tablero turno fichaSel)) (define bpawn (bitmap "b-peon.png")) (define brook (bitmap "b-torre.png")) (define bcaballo (bitmap "b-caballo.png")) (define bbish (bitmap "b-arfil.png")) (define bquee (bitmap "b-reina.png")) (define bking (bitmap "b-rey.png")) (define wpawn (bitmap "w-peon.png")) (define wrook (bitmap "w-torre.png")) (define wcaballo (bitmap "w-caballo.png")) (define wbish (bitmap "w-arfil.png")) (define wquee (bitmap "w-reina.png")) (define wking (bitmap "w-rey.png")) (define board (bitmap "board.jpg")) This is the board that is a list of lists (define tableroini (list (list torreb caballob arfilb reinab reyb arfilb caballob torreb) (list peonb peonb peonb peonb peonb peonb peonb peonb) (list empty empty empty empty empty empty empty empty) (list empty empty empty empty empty empty empty empty) (list empty empty empty empty empty empty empty empty) (list empty empty empty empty empty empty empty empty) (list peonw peonw peonw peonw peonw peonw peonw peonw) (list torrew caballow arfilw reinaw reyw arfilw caballow torrew))) I did this to save the state of the game: (define (Guardar-en-archivo archivo) (write-file (string-append Subcarpeta archivo ".txt") "game state" )) But not as you insert the game state on "game state" for me to save the game How I can do this ?

    Read the article

  • State of Texas delivers Private Cloud Services powered by Oracle Technology

    - by Anand Akela
    State of Texas moved to private cloud infrastructure and delivering Infrastructure as a Service , Database as a Service and other Platform as a Service offerings to their 28 state agencies. Todd Kimbriel, Director of eGovernment Division at State of Texas attended Oracle Open World and talked with Oracle's John Foley about their private cloud services offering. Later, Todd participated in the keynote panel of Database as a Service Online Forum> along with Carl Olofson,IDC analyst , Juan Loaiza,SVP Oracle and couple of other Oracle customers. He discussed the IT challenges of  government organizations like state of Texas and the benefits of transitioning to Private cloud including database as a service .

    Read the article

  • script engine with no global environment (java)

    - by user1886930
    I am curious about how global variables are handled by script engines. I am looking for a script engine that does not preserve the state of global variables upon invocation. Are there such engines out there? We are looking for a scripting language we can use under the script engine API for Java. When making multiple invocations of a script engine, top-level calls to eval() or evaluate() method preserves the state of global variables, meaning that consequent calls to eval() will use the global variables as they were left by the last invocation. Is there a script engine that does not preserve the state, or provides the ability to reset the state, so that global variables are at their initial state every time the script engine is invoked?

    Read the article

  • SNMP closed state in CentOS

    - by anksoWX
    I'm having a problem here, I've added to my IPtables rules this: -A INPUT -p tcp -m state --state NEW -m tcp --dport 161 -j ACCEPT -A INPUT -p udp -m state --state NEW -m udp --dport 161 -j ACCEPT but when I scan with nmap or any other tool it says this: Not shown: 998 filtered ports PORT STATE SERVICE 22/tcp open ssh 161/tcp closed snmp also when I am doing: netstat -apn | grep snmpd tcp 0 0 127.0.0.1:199 0.0.0.0:* LISTEN 3669/snmpd<br> udp 0 0 0.0.0.0:161 0.0.0.0:* 3669/snmpd<br> unix 2 [ ] DGRAM 226186 3669/snmpd Also: service iptables status Table: filter Chain INPUT (policy ACCEPT) num target prot opt source destination 1 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED 2 ACCEPT icmp -- 0.0.0.0/0 0.0.0.0/0 3 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 4 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:161 5 ACCEPT udp -- 0.0.0.0/0 0.0.0.0/0 state NEW udp dpt:161 6 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:22 7 REJECT all -- 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibited Chain FORWARD (policy ACCEPT) num target prot opt source destination 1 REJECT all -- 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibited Chain OUTPUT (policy ACCEPT) num target prot opt source destination Any idea what's going on? There is no UDP in closed/open state. what do I have to do?

    Read the article

  • Pure functional programming and game state

    - by Fu86
    Is there a common technique to handle state (in general) in a functional programming language? There are solutions in every (functional) programming language to handle global state, but I want to avoid this as far as I could. All state in a pure functional manner are function parameters. So I need to put the whole game state (a gigantic hashmap with the world, players, positions, score, assets, enemies, ...)) as a parameter to all functions which wants to manipulate the world on a given input or trigger. The function itself picks the relevant information from the gamestate blob, do something with it, manipulate the gamestate and return the gamestate. But this looks like a poor mans solution for the problem. If I put the whole gamestate into all functions, there is no benefit for me in contrast to global variables or the imperative approach. I could put just the relevant information into the functions and return the actions which will be taken for the given input. And one single function apply all the actions to the gamestate. But most functions need a lot of "relevant" information. move() need the object position, the velocity, the map for collision, position of all enemys, current health, ... So this approach does not seem to work either. So my question is how do I handle the massive amount of state in a functional programming language -- especially for game development?

    Read the article

  • State machine interpreters

    - by saadtaame
    I wrote my own state machine tool in C and at this point I'm faced with two choices for specifying state machines. Crafting a little language and writing a interpreter. Writing a compiler for that language. I know the advantages/disadvantages of each. I'd like to know what choices game programmers have made for their games. If you've used a state machine in your game in any form, I'd be interested in knowing how you did it.

    Read the article

  • is it valid that a state machine can have more than one possible state for some transition?

    - by shankbond
    I have a requirement for a workflow which I am trying to model as a state machine, I see that there is more than one outcome of a given transition(or activity). Is it valid for a state machine to have more than one possible states, but only one state will be true at a given time? Note: This is my first attempt to model a state machine. Eg. might be: s1-t1-s2 s1-t1-s3 s1-t1-s4 where s1, s2, s3, s4 are states and t1 is transition/activity. A fictitious real world example might be: For a human, there can be two states: hungry, not hungry A basket can have only one item from: apple, orange. So, to model it we will have: hungry-pick from basket-apple found hungry-pick from basket-orange found apple found-eat-not hungry orange found-take juice out of it and then drink- not hungry

    Read the article

  • Iptables state tracking

    - by complexgeek
    Hi there. I've just taken over administration of a fairly complex firewall ruleset for a firewall box running Fedora Core 12, and there's one thing about it that is puzzling me. When I run nmap on the gateway from outside the network, I see all the expected services, but also sunrpc on port 111. The INPUT chain has DEFAULT DROP set, and there is no rule allowing port 111. As best I can tell (watching the packet counters before/during/after the scan) it's being allowed by the rule: "-m state --state RELATED,ESTABLISHED -j ACCEPT" but I don't understand why a brand new TCP connection would be considered RELATED or ESTABLISHED. Any suggestions would be greatly appreciated. EDIT: Conntrack modules: nf_conntrack_netlink 14925 0 nfnetlink 3479 1 nf_conntrack_netlink nf_conntrack_irc 5206 1 nf_nat_irc nf_conntrack_proto_udplite 3138 0 nf_conntrack_h323 62110 1 nf_nat_h323 nf_conntrack_proto_dccp 6878 0 nf_conntrack_sip 16921 1 nf_nat_sip nf_conntrack_proto_sctp 11131 0 nf_conntrack_pptp 10673 1 nf_nat_pptp nf_conntrack_sane 5458 0 nf_conntrack_proto_gre 6574 1 nf_conntrack_pptp nf_conntrack_amanda 2796 1 nf_nat_amanda nf_conntrack_ftp 11741 1 nf_nat_ftp nf_conntrack_tftp 4665 1 nf_nat_tftp nf_conntrack_netbios_ns 1534 0 nf_conntrack_ipv6 18504 2 ipv6 279399 40 ip6t_REJECT,nf_conntrack_ipv6 INPUT chain on the filter table: -A INPUT -s 192.168.200.10/32 -p tcp -m tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT -A INPUT -s 127.0.0.0/8 -i lo -j ACCEPT -A INPUT -p udp -m udp --sport 67:68 --dport 67:68 -j ACCEPT -A INPUT -d 192.168.200.5/32 -i eth0 -j ACCEPT -A INPUT -d 192.168.1.2/32 -i eth0 -j ACCEPT -A INPUT -d {public_ip}/32 -i ppp0 -p tcp -m multiport --dports 22,80,443 -j ACCEPT -A INPUT -d {public_ip}/32 -i ppp0 -p tcp -m multiport --sports 22,25,80,443 -j ACCEPT -A INPUT -d {public_ip}/32 -i ppp0 -p udp -m udp --dport 1194 -j ACCEPT -A INPUT -d {public_ip}/32 -i ppp0 -p udp -m udp --sport 1194 -j ACCEPT -A INPUT -d {public_ip}/32 -i ppp0 -p udp -m multiport --sports 53,123 -j ACCEPT -A INPUT -d {public_ip}/32 -i ppp0 -p icmp -m icmp --icmp-type 8 -j ACCEPT -A INPUT -i eth0 -m state --state NEW -j ACCEPT -A INPUT -d {public_ip}/32 -m state --state NEW -j ACCEPT -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT eth0 is connected to the internal network, eth3 is connected to an ADSL modem in bridge mode, ppp0 is the WAN connection tunneled over eth3.

    Read the article

  • How to draw an E-R diagram?

    - by Appy
    I am learning DBMS in my college. Recently I was given an assignment to draw a E-R Model of a Bus Reservation system which handles Reservations, Ticketing and cancellations. I understand the theory about E-R model when I study from a book, but it gets confusing when I try to draw one from scratch. How should one proceed? There seem to be a lot of ways to model a E-R diagram for a particular requirement. It's really confusing. Can anyone explain taking Bus reservation System as an example? Here is the model I made (But I am not confident with it because at every step, I could think of many more alternatives!) - Entity_Set Passenger(passengerID,name,age,gender) Entity_Set Ticket(ticketID,status) //Status is either WaitingList , Confirmed or Cancelled Entity_Set Bus (busID,MaxSeats,Type) //Type is Ac or Non-AC Entity_Set Route(routeID,ArrivalTime,DepartureTime,Source,Destination) And a Ternary relationship between Passenger, Ticket and Bus with attributes as passengerID, ticketID, busID . Binary relationship between Bus and Route with attributes as busID, routeID . I have few doubts regarding - 1 . Should we take Time as a composite attribute with Arrival and Departure as its attributes (What's the difference if we take that way?) 2 . The same with Source and Destination. Should they be made into a composite attribute "Place" or something like "Location"? 3. Are there any weak entity sets here? Can you please 'create' a weak entity set and explain? Because I have no idea at all what to take as a Weak entity set?

    Read the article

  • Is it possible that solid state drives (or any faster drive) will make common applications faster even if they are cached?

    - by leladax
    I assumed that solid state drives are insignificant after, say, Firefox is fully brought up and no important disk activity after that is going on. However, I wonder if some kind of 'cached from the disk to the CPU' activity is going on that may make solid state drives (or any faster drive) better. Then again, I suspect that may be depended only on the Bus (or some kind of cache memory drives have). Hrm..

    Read the article

  • Diagram to show code responsibility

    - by Mike Samuel
    Does anyone know how to visually diagram the ways in which the flow of control in code passes between code produced by different groups and how that affects the amount of code that needs to be carefully written/reviewed/tested for system properties to hold? What I am trying to help people visualize are arguments of the form: For property P to hold, nd developers have to write application code, Ca, without certain kinds of errors, and nm maintainers have to make sure that the code continues to not have these kinds of errors over the project lifetime. We could reduce the error rate by educating nd developers and nm maintainers. For us to be confident that the property holds, ns specialists still need to test or check |Ca| lines of code and continue to test/check the changes by nm maintainers. Alternatively, we could be confident that P holds if all code paths that could violate P went through tool code, Ct, written by our specialists. In our case, test suites alone cannot give confidence that P holdsnd » nsnm ns|Ca| » |Ct| so writing and maintaining Ct is economical, frees up our developers to worry about other things, and reduces the ongoing education commitment by our specialists. or those conditions do not hold, so focusing on education and testing is preferable. Example 1 As a concrete example, suppose we want to ensure that our web-service only produces valid JSON output. Our web-service provides several query and mutation operators that can be composed in interesting ways. We could try to educate everyone who maintains those operations about the JSON syntax, the importance of conformance, and libraries available so that when they write to an output buffer, every possible sequence of appends results in syntactically valid JSON. Alternatively, we don't expose an output stream handle to application code, and instead expose a JSON sink so that every code path that writes a response is channeled through a JSON sink that is written and maintained by a specialist who knows JSON syntax and can use well-written libraries to produce only valid output. Example 2 We need to make sure that a service that receives a URL from an untrusted source and tries to fetch its content does not end up revealing sensitive files from the file-system, like file:///etc/passwd. If there is a single standard way that any developer familiar with the application language's libraries would use to fetch URLs, which has file-system access turned off by default, then simply educating developers about the standard mechanism, and testing that file probing fails for some inputs, will probably be sufficient.

    Read the article

  • How can I create a class diagram with NetBeans' 6.8 UML module?

    - by Karussell
    It seems to me the UML module of NetBeans is a bit too much hidden. In NetBeans 6.5 it was very easy to create an UML diagram. No plugin installation necessary or sth. like. Read my post where I found a zip file to install the UML module. And now, after this procedure, I got the UML module back, but it seems to me that I cannot create class diagram with it. Do you know how I can do this with NetBeans 6.8? Update1: There seems to be no support Update2: Nevertheless somebody seems to got it working.

    Read the article

  • Understanding C# async / await (1) Compilation

    - by Dixin
    Now the async / await keywords are in C#. Just like the async and ! in F#, this new C# feature provides great convenience. There are many nice documents talking about how to use async / await in specific scenarios, like using async methods in ASP.NET 4.5 and in ASP.NET MVC 4, etc. In this article we will look at the real code working behind the syntax sugar. According to MSDN: The async modifier indicates that the method, lambda expression, or anonymous method that it modifies is asynchronous. Since lambda expression / anonymous method will be compiled to normal method, we will focus on normal async method. Preparation First of all, Some helper methods need to make up. internal class HelperMethods { internal static int Method(int arg0, int arg1) { // Do some IO. WebClient client = new WebClient(); Enumerable.Repeat("http://weblogs.asp.net/dixin", 10) .Select(client.DownloadString).ToArray(); int result = arg0 + arg1; return result; } internal static Task<int> MethodTask(int arg0, int arg1) { Task<int> task = new Task<int>(() => Method(arg0, arg1)); task.Start(); // Hot task (started task) should always be returned. return task; } internal static void Before() { } internal static void Continuation1(int arg) { } internal static void Continuation2(int arg) { } } Here Method() is a long running method doing some IO. Then MethodTask() wraps it into a Task and return that Task. Nothing special here. Await something in async method Since MethodTask() returns Task, let’s try to await it: internal class AsyncMethods { internal static async Task<int> MethodAsync(int arg0, int arg1) { int result = await HelperMethods.MethodTask(arg0, arg1); return result; } } Because we used await in the method, async must be put on the method. Now we get the first async method. According to the naming convenience, it is named MethodAsync. Of course a async method can be awaited. So we have a CallMethodAsync() to call MethodAsync(): internal class AsyncMethods { internal static async Task<int> CallMethodAsync(int arg0, int arg1) { int result = await MethodAsync(arg0, arg1); return result; } } After compilation, MethodAsync() and CallMethodAsync() becomes the same logic. This is the code of MethodAsyc(): internal class CompiledAsyncMethods { [DebuggerStepThrough] [AsyncStateMachine(typeof(MethodAsyncStateMachine))] // async internal static /*async*/ Task<int> MethodAsync(int arg0, int arg1) { MethodAsyncStateMachine methodAsyncStateMachine = new MethodAsyncStateMachine() { Arg0 = arg0, Arg1 = arg1, Builder = AsyncTaskMethodBuilder<int>.Create(), State = -1 }; methodAsyncStateMachine.Builder.Start(ref methodAsyncStateMachine); return methodAsyncStateMachine.Builder.Task; } } It just creates and starts a state machine, MethodAsyncStateMachine: [CompilerGenerated] [StructLayout(LayoutKind.Auto)] internal struct MethodAsyncStateMachine : IAsyncStateMachine { public int State; public AsyncTaskMethodBuilder<int> Builder; public int Arg0; public int Arg1; public int Result; private TaskAwaiter<int> awaitor; void IAsyncStateMachine.MoveNext() { try { if (this.State != 0) { this.awaitor = HelperMethods.MethodTask(this.Arg0, this.Arg1).GetAwaiter(); if (!this.awaitor.IsCompleted) { this.State = 0; this.Builder.AwaitUnsafeOnCompleted(ref this.awaitor, ref this); return; } } else { this.State = -1; } this.Result = this.awaitor.GetResult(); } catch (Exception exception) { this.State = -2; this.Builder.SetException(exception); return; } this.State = -2; this.Builder.SetResult(this.Result); } [DebuggerHidden] void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine param0) { this.Builder.SetStateMachine(param0); } } The generated code has been refactored, so it is readable and can be compiled. Several things can be observed here: The async modifier is gone, which shows, unlike other modifiers (e.g. static), there is no such IL/CLR level “async” stuff. It becomes a AsyncStateMachineAttribute. This is similar to the compilation of extension method. The generated state machine is very similar to the state machine of C# yield syntax sugar. The local variables (arg0, arg1, result) are compiled to fields of the state machine. The real code (await HelperMethods.MethodTask(arg0, arg1)) is compiled into MoveNext(): HelperMethods.MethodTask(this.Arg0, this.Arg1).GetAwaiter(). CallMethodAsync() will create and start its own state machine CallMethodAsyncStateMachine: internal class CompiledAsyncMethods { [DebuggerStepThrough] [AsyncStateMachine(typeof(CallMethodAsyncStateMachine))] // async internal static /*async*/ Task<int> CallMethodAsync(int arg0, int arg1) { CallMethodAsyncStateMachine callMethodAsyncStateMachine = new CallMethodAsyncStateMachine() { Arg0 = arg0, Arg1 = arg1, Builder = AsyncTaskMethodBuilder<int>.Create(), State = -1 }; callMethodAsyncStateMachine.Builder.Start(ref callMethodAsyncStateMachine); return callMethodAsyncStateMachine.Builder.Task; } } CallMethodAsyncStateMachine has the same logic as MethodAsyncStateMachine above. The detail of the state machine will be discussed soon. Now it is clear that: async /await is a C# language level syntax sugar. There is no difference to await a async method or a normal method. As long as a method returns Task, it is awaitable. State machine and continuation To demonstrate more details in the state machine, a more complex method is created: internal class AsyncMethods { internal static async Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3) { HelperMethods.Before(); int resultOfAwait1 = await MethodAsync(arg0, arg1); HelperMethods.Continuation1(resultOfAwait1); int resultOfAwait2 = await MethodAsync(arg2, arg3); HelperMethods.Continuation2(resultOfAwait2); int resultToReturn = resultOfAwait1 + resultOfAwait2; return resultToReturn; } } In this method: There are multiple awaits. There are code before the awaits, and continuation code after each await After compilation, this multi-await method becomes the same as above single-await methods: internal class CompiledAsyncMethods { [DebuggerStepThrough] [AsyncStateMachine(typeof(MultiCallMethodAsyncStateMachine))] // async internal static /*async*/ Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3) { MultiCallMethodAsyncStateMachine multiCallMethodAsyncStateMachine = new MultiCallMethodAsyncStateMachine() { Arg0 = arg0, Arg1 = arg1, Arg2 = arg2, Arg3 = arg3, Builder = AsyncTaskMethodBuilder<int>.Create(), State = -1 }; multiCallMethodAsyncStateMachine.Builder.Start(ref multiCallMethodAsyncStateMachine); return multiCallMethodAsyncStateMachine.Builder.Task; } } It creates and starts one single state machine, MultiCallMethodAsyncStateMachine: [CompilerGenerated] [StructLayout(LayoutKind.Auto)] internal struct MultiCallMethodAsyncStateMachine : IAsyncStateMachine { public int State; public AsyncTaskMethodBuilder<int> Builder; public int Arg0; public int Arg1; public int Arg2; public int Arg3; public int ResultOfAwait1; public int ResultOfAwait2; public int ResultToReturn; private TaskAwaiter<int> awaiter; void IAsyncStateMachine.MoveNext() { try { switch (this.State) { case -1: HelperMethods.Before(); this.awaiter = AsyncMethods.MethodAsync(this.Arg0, this.Arg1).GetAwaiter(); if (!this.awaiter.IsCompleted) { this.State = 0; this.Builder.AwaitUnsafeOnCompleted(ref this.awaiter, ref this); } break; case 0: this.ResultOfAwait1 = this.awaiter.GetResult(); HelperMethods.Continuation1(this.ResultOfAwait1); this.awaiter = AsyncMethods.MethodAsync(this.Arg2, this.Arg3).GetAwaiter(); if (!this.awaiter.IsCompleted) { this.State = 1; this.Builder.AwaitUnsafeOnCompleted(ref this.awaiter, ref this); } break; case 1: this.ResultOfAwait2 = this.awaiter.GetResult(); HelperMethods.Continuation2(this.ResultOfAwait2); this.ResultToReturn = this.ResultOfAwait1 + this.ResultOfAwait2; this.State = -2; this.Builder.SetResult(this.ResultToReturn); break; } } catch (Exception exception) { this.State = -2; this.Builder.SetException(exception); } } [DebuggerHidden] void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { this.Builder.SetStateMachine(stateMachine); } } Once again, the above state machine code is already refactored, but it still has a lot of things. More clean up can be done if we only keep the core logic, and the state machine can become very simple: [CompilerGenerated] [StructLayout(LayoutKind.Auto)] internal struct MultiCallMethodAsyncStateMachine : IAsyncStateMachine { // State: // -1: Begin // 0: 1st await is done // 1: 2nd await is done // ... // -2: End public int State; public TaskCompletionSource<int> ResultToReturn; // int resultToReturn ... public int Arg0; // int Arg0 public int Arg1; // int arg1 public int Arg2; // int arg2 public int Arg3; // int arg3 public int ResultOfAwait1; // int resultOfAwait1 ... public int ResultOfAwait2; // int resultOfAwait2 ... private Task<int> currentTaskToAwait; /// <summary> /// Moves the state machine to its next state. /// </summary> public void MoveNext() // IAsyncStateMachine member. { try { switch (this.State) { // Original code is split by "await"s into "case"s: // case -1: // HelperMethods.Before(); // MethodAsync(Arg0, arg1); // case 0: // int resultOfAwait1 = await ... // HelperMethods.Continuation1(resultOfAwait1); // MethodAsync(arg2, arg3); // case 1: // int resultOfAwait2 = await ... // HelperMethods.Continuation2(resultOfAwait2); // int resultToReturn = resultOfAwait1 + resultOfAwait2; // return resultToReturn; case -1: // -1 is begin. HelperMethods.Before(); // Code before 1st await. this.currentTaskToAwait = AsyncMethods.MethodAsync(this.Arg0, this.Arg1); // 1st task to await // When this.currentTaskToAwait is done, run this.MoveNext() and go to case 0. this.State = 0; MultiCallMethodAsyncStateMachine that1 = this; // Cannot use "this" in lambda so create a local variable. this.currentTaskToAwait.ContinueWith(_ => that1.MoveNext()); break; case 0: // Now 1st await is done. this.ResultOfAwait1 = this.currentTaskToAwait.Result; // Get 1st await's result. HelperMethods.Continuation1(this.ResultOfAwait1); // Code after 1st await and before 2nd await. this.currentTaskToAwait = AsyncMethods.MethodAsync(this.Arg2, this.Arg3); // 2nd task to await // When this.currentTaskToAwait is done, run this.MoveNext() and go to case 1. this.State = 1; MultiCallMethodAsyncStateMachine that2 = this; this.currentTaskToAwait.ContinueWith(_ => that2.MoveNext()); break; case 1: // Now 2nd await is done. this.ResultOfAwait2 = this.currentTaskToAwait.Result; // Get 2nd await's result. HelperMethods.Continuation2(this.ResultOfAwait2); // Code after 2nd await. int resultToReturn = this.ResultOfAwait1 + this.ResultOfAwait2; // Code after 2nd await. // End with resultToReturn. this.State = -2; // -2 is end. this.ResultToReturn.SetResult(resultToReturn); break; } } catch (Exception exception) { // End with exception. this.State = -2; // -2 is end. this.ResultToReturn.SetException(exception); } } /// <summary> /// Configures the state machine with a heap-allocated replica. /// </summary> /// <param name="stateMachine">The heap-allocated replica.</param> [DebuggerHidden] public void SetStateMachine(IAsyncStateMachine stateMachine) // IAsyncStateMachine member. { // No core logic. } } Only Task and TaskCompletionSource are involved in this version. And MultiCallMethodAsync() can be simplified to: [DebuggerStepThrough] [AsyncStateMachine(typeof(MultiCallMethodAsyncStateMachine))] // async internal static /*async*/ Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3) { MultiCallMethodAsyncStateMachine multiCallMethodAsyncStateMachine = new MultiCallMethodAsyncStateMachine() { Arg0 = arg0, Arg1 = arg1, Arg2 = arg2, Arg3 = arg3, ResultToReturn = new TaskCompletionSource<int>(), // -1: Begin // 0: 1st await is done // 1: 2nd await is done // ... // -2: End State = -1 }; multiCallMethodAsyncStateMachine.MoveNext(); // Original code are moved into this method. return multiCallMethodAsyncStateMachine.ResultToReturn.Task; } Now the whole state machine becomes very clean - it is about callback: Original code are split into pieces by “await”s, and each piece is put into each “case” in the state machine. Here the 2 awaits split the code into 3 pieces, so there are 3 “case”s. The “piece”s are chained by callback, that is done by Builder.AwaitUnsafeOnCompleted(callback), or currentTaskToAwait.ContinueWith(callback) in the simplified code. A previous “piece” will end with a Task (which is to be awaited), when the task is done, it will callback the next “piece”. The state machine’s state works with the “case”s to ensure the code “piece”s executes one after another. Callback If we focus on the point of callback, the simplification  can go even further – the entire state machine can be completely purged, and we can just keep the code inside MoveNext(). Now MultiCallMethodAsync() becomes: internal static Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3) { TaskCompletionSource<int> taskCompletionSource = new TaskCompletionSource<int>(); try { // Oringinal code begins. HelperMethods.Before(); MethodAsync(arg0, arg1).ContinueWith(await1 => { int resultOfAwait1 = await1.Result; HelperMethods.Continuation1(resultOfAwait1); MethodAsync(arg2, arg3).ContinueWith(await2 => { int resultOfAwait2 = await2.Result; HelperMethods.Continuation2(resultOfAwait2); int resultToReturn = resultOfAwait1 + resultOfAwait2; // Oringinal code ends. taskCompletionSource.SetResult(resultToReturn); }); }); } catch (Exception exception) { taskCompletionSource.SetException(exception); } return taskCompletionSource.Task; } Please compare with the original async / await code: HelperMethods.Before(); int resultOfAwait1 = await MethodAsync(arg0, arg1); HelperMethods.Continuation1(resultOfAwait1); int resultOfAwait2 = await MethodAsync(arg2, arg3); HelperMethods.Continuation2(resultOfAwait2); int resultToReturn = resultOfAwait1 + resultOfAwait2; return resultToReturn; Yeah that is the magic of C# async / await: Await is not to wait. In a await expression, a Task object will be return immediately so that execution is not blocked. The continuation code is compiled as that Task’s callback code. When that task is done, continuation code will execute. Please notice that many details inside the state machine are omitted for simplicity, like context caring, etc. If you want to have a detailed picture, please do check out the source code of AsyncTaskMethodBuilder and TaskAwaiter.

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >