Using the StateMachineCompiler(SMC) in own code - c#

Hello i want to use the State Machine Compiler (SMC) with C#
http://smc.sourceforge.net/
i have created the sm-File to describe the state machine and generated c# code from it.
Then i created my own class MyClass,add the generated class which was generated with smc and implement the methods.
My Problem is how can i run this statemachine? With a While-loop, a async call or the Task Library ? What is an elegant way?
The Statemachine is a behaivior for sending data throught the serialport. So that the user can call MyClass.Send(Data) and the StateMachine should work behind the curtains.
Can someone give me an example how to use the statemachine in own code?
Regards
rubiktubik

I've used SMC in many application and I was very satisfied with it. I hit the same problem as you. SMC generates code for C# which is synchronous and linear. This means if you issue a transaction by calling fsm.YourTransaction() and by chance somewhere in the middle of that transaction you issue another transaction, it would be directly called. It is very dangerous, because it breaks the base principle of a state machine - that transactions are atomic and the system is guaranteed to be in single state, or single transition all the time.
When I realized this hidden problem I implemented an asynchronous layer above the state machine code generated by SMC. Unfortunately I cannot provide you with the code, because is licensed, but I can describe the principle here.
I replaced direct method calls with asynchronous event processing: there is a queue awaiting transactions. Transactions are represented by strings, which must be the same as transaction methods in fsm. They are removed from the queue one by one in an independent thread. Transaction string is transformed to a fsm method call.
This concept proved to work very well in many critical applications. It is rather simple to implement and easy to extend with new features.
Final form of this asynchronous layer had these additional features:
Perfect logging: all transactions and their arguments, time of arrival, time of processing ...etc.
Possibility to replace the independent thread with an external thread - sometimes it is better to process things in thread provided from outside (Windows GUI is very sensitive to external thread calls...)
Preprocessing of transactions - sometimes the system was expected to change state only if a sequence of transaction occured. It is rather clumsy to achieve it directly with SMC. I implemented so called "transaction transformations" - it was possible to declare how a set of transactions is transformed into a single transaction.

Related

Logging in Multithreading Async Code

I have a multithreading application with async processing (which by itself uses many threads). Without async, it would be easy to log and then trace the execution flow as one simply puts current thread identifier to the log and thus you can see which log line was executed by which thread.
How to achive a similar thing in async environment? Often when await is called, the following code is assigned to another thread (and I am OK with that, I trust the thread pool manager to do these assignments for me effectively). The problem is that suddenly I do not have this fixed thread ID for the execution flow and it is hard to put the two parts together.
Is there any identifier of the task that would be kept among the whole code? I mean let's say there are 5x await calls in a method. With thread ID, I can see in the logs up to 6 different IDs. I would want one thing and I would prefer if it is there already (I know I can create an object and pass it to my log function, over and over again, but if there was something already, it would be better).
Is Task.Id or Task.CurrentId suitable for this purpose, or is it something else?
What you're referring to is a "correlation id", or what log4net calls a "nested diagnostic context" (NDC). Whatever logging framework you have should have one already, most likely one that already works with async.
If you need to build your own, I'd recommend putting an id (or an immutable stack of ids) into an AsyncLocal<T> (which is essentially LogicalSetData but with an easier-to-use and more portable API). Note that the async contextual data should be immutable. See my blog for more info.
I think the answer to "is [there] a ready to go identifier that can be used" is probably no, but you can use CallContext, and specifically LogicalSetData, not just SetData(), and for instance add a GUID that will flow across all async-await forks.

Asynchronous fire and forget in c#

Currently I am about to develop logging for a c# application into a SQL server table.
I have a designated class called Logger that has a static method writeToLog().
I just want to call that static function without block the calling thread.
How is this possible in C# clean and fast?
The functions don't return anything they are just fire and forget.
Thanks for you advice
There is the chance that the serveral available logging libraries out there have spent some thoughts about performance.
If you still need to develop a light weight solution yourself I think of two ways.
1.) Create a Task that runs the logging function, without awaiting them
2.) The Log-Method saves the Log-Information in a queue that is written to the SQL-database with a background thread.
I would recommend the second way, because the logging itself can be done in a synchronous function call without the Task creation overhead.
Another argument for this approach is that it is possible to gurantee the order of log messages. By using a Task for each single message the order of execution is not defined.
And a last argument: It might be more performant to write blocks of messages to the SQL table. By using the queue you will be able write messages in a bulk operation.

Asynchronous start/stop state transitions

I have a third-party object with asynchronous start and stop methods. Each start and stop may fail with exception. The object is not re-entrant, i.e. I can only call its start or stop method after the previous start/stop has completed.
I need to have a class that handles those transitions to the correct (=last asked) state, while minimizing the number of transitions, allowing my client to submit any number of start/stop requests from any thread at any time.
Currently, I’ve implemented that functionality as endless loop in the async method, however It’s too complex, the loop is over 4 pages long, on each iteration I need to manually switch between 8 states (with the following 3 bits: need to be started/stopped, did tried to start/stop, did failed/succeeded). It smells.
I have a feeling I might be missing something obvious here.
And also that my code looks somewhat similar to what compiler does when compiling an async function.
Is there a better way to approach the problem?
Sounds like you need a mutex around the calls. You need to block any other code from calling these methods until the methods return (or signal that they are done).
I would simply wrap the object and add a mutex for the calls. That way you can guarantee that if you don't make two calls at the same time.
You don't need to block on the mutex. You can use something like a producer/consumer queue or a threadpool to synchornize the access.
If you are in a single threaded environment you can also do it with a simple queue (and skip all the multi-threaded objects).

Using TransactionScope when integration testing web apis

At the moment, I'm doing something similar to this to integration test a library that communicates with our API controllers, and so far so good, but I've run into a snag. In all of our other integration tests, we run the test inside an MSDTC transaction at isolation level ReadCommitted so that each one gets its own little private session with the databases and such, and at the end of each test, the transactions are rolled back. ..But that doesn't work for these tests because the transactions are per-thread and all of the HttpClient/HttpServer methods are asynchronous, so the work is done on a different thread than the main one for that test, doesn't have an ambient transaction to subscribe to, and goes right along and commits.
I've come across a few posts about how to open a TransactionScope on one thread and then create a dependent transaction to be passed to a new task via a closure, but I have no idea how to apply that to an HttpClient that's connected to an in-memory HttpServer. I suspect I'm just not thinking about it the right way, but that's about all I have to go on.
What would make sense/work/etc? I have full control over the creation of the HttpServer and the HttpClient that will connect to it, but I'm at a loss as to what to do with them.
UPDATE:
Some progress has been made- I wrote a message handler that can create a dependent transaction on the worker thread if Transaction.Current is populated when it gets there, and for some of my calls it is, but for others it isn't, and I'm wondering if I may be chasing shadows - like, there's a lot of ContinueWith around, and I think it's executed on the calling thread (which would naturally have a transaction) if the antecedent task is already complete.
Would it be possible just to run the whole thing synchronously and carry the test's thread all the way through? I've experimented some with ContinueWith'ing synchronously without much success..
If you aren't dead-set on using a real HTTP connection, you could call the interfaces directly via code (by using an assembly reference) from a test framework that allows you to do per-session or per-test start-up and shut-down work (such as MSTest's class and test initialize functions). In this case, you would open a TransactionScope that is shared across the class in a member variable and dispose it in the class or test shut-down function. Because you didn't call .Commit(), it will roll-back the operations that occurred during the transaction.
As it turns out, the HttpClient and HttpServer weren't spinning up background threads - rather, I had some errant Task.StartNew's in my code that were causing the problem. Removing those got me going.

Do async calls introduce a security vulnerability

Just read a requirements document.
One of the requirements is that there should not be any async calls. It appears to be a security requirement.
Question is what are the security vulnerabilities of using async calls? Or any other reason to ban them?
All transport is over Https/SSL. The calls are web services between 2 systems.
There is nothing intrinsically wrong with asynchronous calls, although they can be harder to work with.
The only thing I can think of is that there might be a slight chance that the "completed" event could be spoofed and hence feed malicious data to your application.
However, I would have thought that the chances of that were remote.
Asynchronous calls can often have race conditions, which may, sometimes, lead to security vulnerabilities.
However, banning them outright for this reason is like banning the use of signed integers because they can sometimes lead to security vulnerabilities - the solution is understanding the problem, not sweeping it under the rug.
An asynchronous call, defined as one thread in a process spawning another thread to make the call and listen for the result while the parent thread continues on its business, is no more or less secure than the same call made synchronously. The only difference between the two, from the perspective of an outside observer of the process, is that a side thread is the one being blocked while waiting for the results of the call, instead of the main thread. The new thread gets a new stack and execution pointer, but shares the heap with all other threads of a process, and threads can access variables in other threads' stacks by reference. It's the same program, executing in the same memory space, it is just having its code executed from two places instead of one.
Further, it may be impossible to write a C# program that does not have any asynchronous operations; there are many such operations built into the runtime. Garbage collection, for instance, and threads used by the runtime to talk to various I/O layers. Event-driven UI programming is heavily threaded; the "main thread" of your program is called by the runtime's "UI thread" whenever the user does something; otherwise it's just waiting.
With asynchronous calls it is harder to keep proper context of the call as final portion of the call will be usually executed on random thread.Impersonation, thread local objects setup by runtime (like HttpContext.Current in ASP.Net), regular static/thread local objects need to be correctly restored before running code that may rely on them.
Not allowing asynchronous calls guarantees problems - non responsive UI in desktop applications and performance problems with services applications.
Also as everyone else pointed out writing asynchronous code is harder than synchronous. There are libraries that help writing such code - i.e. http://msdn.microsoft.com/en-us/magazine/cc546608.aspx

Categories

Resources