D
D
Damir2016-02-16 12:54:23
WPF
Damir, 2016-02-16 12:54:23

How to make a state machine in WPF?

Good day to all!
I have the following task: I
need to rewrite the state machine for WPF, which was previously done using WorkFlow. The main condition is that views (xaml) must be loaded dynamically from files.
Briefly about my decision:
There is a window, an element of type Frame is placed in it. Its Content property is bound to the ViewModel's Page CurrentPage type property. Accordingly, the Frame's DataContext is my ViewModel.
In the constructor of the ViewModel, an instance of the state machine is created, in which it runs an infinite while loop in a separate STA thread Thread. This thread checks the jump queue at regular intervals. As soon as it finds an entry in the transition queue, the new state is loaded. I load the view like this:

using (var fs = new FileStream(ViewFilePath, FileMode.Open))
                    {
                        pageToLoad = XamlReader.Load(fs) as Page;
                    }

There are no problems. After successfully loading the view, we call the onStateChanged event in the ViewModel. Where the CurrentPage property is set to newState.Page.
This is where the problem arises. When trying to display a new window, an error occurs:

Exception:Thrown: "The calling thread cannot access this object because another thread owns this object." (System.InvalidOperationException)
A System.InvalidOperationException was thrown: "The calling thread cannot access this object because another thread owns this object."

Actually, this is the question. How can I overcome this error so that it displays the CurrentPage for me?
Although it is possible in general the approach is a curve and someone can share a more competent solution.
Thank you for your attention. I really hope for your help.
I am attaching the test project sources:
Test project

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Damir, 2016-02-17
@YaMirok

Basically, I did it a little differently. I load the new state in the same thread where I create the state machine. I used AsyncOperation.

A
Aleksej, 2016-02-16
@Shwed_Berlin

In one of the projects, I implemented a state machine using Appccelerate Statemachine .
Everything is very simple, for me it turned out to be easier than the Workflow Foundation.
In my case, I managed the same flow. Think about whether you can get by with one thread, otherwise the same rake will arise, because your problem is with the thread, and not with the machine.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question