System.Windows.Forms.AxHost.InvalidActiveXStateException was unhandled - c#

I am continuously struggling with this exception
An unhandled exception of type 'System.Windows.Forms.AxHost.InvalidActiveXStateException' occurred in AxInterop.SBXPCLib.dll
any help please, am i missing some thing.

Try this,it will solve your problem:
For each and every active x control, it is needed to create it first, so that all the events and handles should be initialized.
So try this:
axMDocView1.CreateControl()

The answer by Vishal is Fulfill your requirement but here I wanted to add one more thing with it. If you wanted to reflected this changes via all the threads and not only by calling thread (in multiple thread scenario) then use
axMDocView1.CreateControl();
axMDocView1.SkinAllThreads();
Actually in multiple threading scenario if your skinning code is in one of the thread then may be it is not reflect change for other current thread so at that time this code is play important role in it.

Related

FolderBrowseDialog STAThread error in background worker

Good day,
I'm getting an error very similar to the one discussed here (among other sources here and elsewhere): STAThread missing, but it is there
The difference is that in my case I am using multi-threading. A BackgroundWorker is generating documents and when it's done, a FolderBrowseDialog will pop up to allow the user to choose a location to save the generated documents. So I can understand why I'm receiving this error. The reason I chose to put the FolderBrowseDialog in the BackgroundWorker events and related code is because then I have direct access to the path in stead of passing the string from one thread to the other.
Funny thing though, PrintDialog works but SaveFileDialog and FolderBrowseDialog throws this error.
I would just like to hear your thoughts. Would it be best to move the FolderBrowseDialog out of the BackgroundWorker code? Should I implement a custom FolderBrowseDialog? Is there any way around this?
Thanks in advance for comments and advice and to everyone taking the time to consider my question; much appreciated.
Kind regards
Is the FolderBrowseDialog being called in the RunWorkerCompleted callback or is it being called in the DoWork callback? If you're calling it from the DoWork callback, you'll need to use the SynchronizationContext the BackgroundWorker was created in and use the Send method to show the FolderBrowseDialog.
http://thedersen.com/2010/05/23/showing-modal-dialogs-from-a-background-thread/ is the closest example I can find on the web. In that example, the Worker class is used to store the SynchronizationContext.

Invalid Operation Exception - "Cross-thread operation not valid: Control 'TextBox1' accessed from a thread other than the thread it was created on."

"If necessity is the mother of
invention, I'd like to kill the guy
who invented this."
-Jimmy Buffet
I don't care if 100 people with a million reputation jump down my throat for saying this, but who ever thought of throwing this exception deserves a fate worse than death.
I have QUITE LITERALLY copied and pasted code from one project to another to populate standard data into a small set of text boxes. In one application, the data is displayed perfectly. The new one I'm working on now, throws this exception of course.
So here is my question - why would one throw it and the other not if the code is the same? Is there a setting in the project settings? Is there a property in the text box that prevents this?
I don't recall setting anything in the project to ignore this exception, but the code is EXACTLY THE SAME.
STAThread attribute set on the thread creating the controls?
Is the populating code called in the UI thread or not? Noone cares whether you did copy the code properly - if the call is on the wrong thread to start with.
I don't want to repeat the error message, but you are trying to modify a control from a thread different than th thread that control was created on.
Take a look at InvokeRequired and Invoke.

WPF custom BalloonTips problem with multithreading

I have read other related question but i cant really get them to relate to this so I thought it were best to ask, Im pretty new to WPF and so on so please bear with me.
I am using this http://www.codeproject.com/KB/WPF/wpf_notifyicon.aspx api to work with custom WPF Windows (in particular FancyBalloon).
However, i'm coming across the following problem, I seem unable to start off BalloonTips in a separate thread ( i need this because i'm parsing emails and hence if there are 3 emails for instance, it displays the first email (that works fine), but when it comes to the second email it crashes with a TargetInvocationException , {"Specified element is already the logical child of another element. Disconnect it first."}.
Thing is, im supposedly working with the same instance and i have attempted calling it to close it before, disposing it etc but to no avail. (then again if i dispose it, i cant create another instance as apparently WPF UI components must be called from a static thread so throughout the looping of emails + displaying balloon, i am trying to use the same BalloonTip.
Any suggestions please? I am really at a loss here and i've been on it for quite a while now :/
I was wondering if there was anyone
In general, WPF controls should be accessed and updated only on the main UI thread. There are thread affinity checks all over the data binding innards that will throw an exception if you assign to a data bound property from any thread that isn't the WPF UI thread, for example.
You can either remove the UI code from your background worker thread, or make judicious use of a SynchronizationContext to invoke from your background thread snippets of code to execute on the UI thread.
If you're new to WPF or new to threading, you should keep the UI stuff out of the background threads. WPF has plenty of complexity to keep you busy without adding the additional headache of threading issues to the mix.
It seems you are adding the same UI element to multiple parent containers at the same time.
For example, if I attempt myStackPanel.Children.Add(myUIElement) concurrently in separate threads, referring to the same UI element object, this would cause the error you are seeing.
If you need the same UI elements for multiple threads, consider cloning them or moving your UI logic to the main thread.

Error handling patterns for multithreaded apps using WF?

I was writing up a long, detailed question, but just scrapped it in favor of a simpler question that I didn't find an answer to here.
Brief app description:
I have a WPF app that spawns several threads, and each thread executes its own WF. What are some of the best ways to handle errors in the threads and WF that will allow user interaction from the GUI side? I definitely plan to handle any low level exceptions in the thread, because I don't want the thread to exit.
Summary of questions:
How have you implemented communication between WF and the thread that starts it? There is WorkflowTerminated, but I don't want the workflow to exit -- I need to fix the problem and let it continue. I assume the only option is using a FaultHandler, but was wondering if there's another way to do it without using an activity block. I am hoping there's a framework out there that I just haven't found yet.
The error from WF needs to get caught by the thread, which then needs to display the error in the GUI. The user will then make a logical choice for recovery, which should then be sent back to the thread, and then to WF. Again, is there something existing out there that I should take a look at?
Even buzzwords / keywords that accomplish what I am describing would be really helpful, and I can do the legwork on researching each of them. However, any additional insight is always welcome. :)
What's worked for me in multi-threaded WPF apps is to have the errant thread invoke a callback method that passes the exception and other info back to the UI thread. Callbacks can have return values, so if your thread can block while waiting for the user to respond, then that can work for you. Remember that the callback will run on the thread that calls it, so any UI updates have to be done via the control's dispatcher. You will have to decide whether all of the threads use the same callback and what kind of synchronization you'll need if there's a chance that multiple threads can throw exceptions simultaneously.
Here's how I ended up solving this problem. But first a little background info:
User clicks a button in the GUI that causes the candy packager to start running. This is done via a command binding in the ViewModel, which then calls a low-level function in the Model. The function in the model launches a thread and executes a state machine.
At some point, the machine will fail. When it does, I compile information about the error and possible (known) recovery methods. I put this into an object and then pass it to the GUI via a callback interface. In the meantime, the worker thread is stuck waiting for an Event to get set.
Eventually, the candy worker will notice the error and will click a button telling the system what to do. This results in two things: 1) it flags one of the recovery methods as the preferred one, and 2) sets the event. Now the worker thread continues on, checks for the preferred error recovery method and transitions into the respective state in the state machine.
This works very well (so far). The part I know is totally lame is the manner in which it checks for the preferred error recovery method. I am essentially setting a string variable, and then comparing this string to a list of known strings. Ultra lame, but I'm not sure of a better way to do this, other than using an enum. Does anyone have recommendations for me?

Multithreading: how to update UI to indicate progress

I've been working on the same project now since Christmas 2008. I've been asked to take it from a Console Application (which just prints out trace statements), to a full Windows App. Sure, that's fine. The only thing is there are parts of the App that can take several minutes to almost an hour to run. I need to multithread it to show the user status, or errors. But I have no idea where to begin.
I've aready built a little UI in WPF. It's very basic, but I'd like to expand it as I need to. The app works by selecting a source, choosing a destination, and clicking start. I would like a listbox to update as the process goes along. Much in the same way SQL Server Installs, each step has a green check mark by its name as it completes.
How does a newbie start multithreading? What libraries should I check out? Any advice would be greatly appreciated.
p.s. I'm currently reading about this library, http://www.codeplex.com/smartthreadpool
#Martin: Here is how my app is constructed:
Engine: Runs all major components in pre-defined order
Excel: Library I wrote to wrap COM to open/read/close/save Workbooks
Library: Library which understands different types of workbook formats (5 total)
Business Classes: Classes I've written to translate Excel data and prep it for Access
Db Library: A Library I've written which uses ADO.NET to read in Access data
AppSettings: you get the idea
Serialier: Save data in-case of app crash
I use everything from LINQ to ADO.NET to get data, transform it, and then output it.
My main requirement is that I want to update my UI to indicate progress
#Frank: What happens if something in the Background Worker throws an Exception (handled or otherwise)? How does my application recieve notice?
#Eric Lippert: Yes, I'm investigating that right now. Before I complicate things.
Let me know if you need more info. Currently I've running this application from a Unit Test, so I guess callig it a Console Application isn't true. I use Resharper to do this. I'm the only person right now who uses the app, but I'd like a more attractive interface
I don't think you specify the version of the CLR you are using, but you might check out the "BackgroundWorker" control. It is a simple way to implemented multiple threads.
The best part, is that it is a part of the CLR 2.0 and up
Update in response to your update: If you want to be able to update the progress in the UI -- for example in a progress bar -- the background worker is perfect. It uses an event that I think is called: ProgressChanged to report the status. It is very elegant. Also, keep in mind that you can have as many instances that you need and can execute all the instances at the same time (if needed).
In response to your question: You could easily setup an example project and test for your question. I did find the following, here (under remarks, 2nd paragraph from the caution):
If the operation raises an exception
that your code does not handle, the
BackgroundWorker catches the exception
and passes it into the
RunWorkerCompleted event handler,
where it is exposed as the Error
property of
System.ComponentModel..::.RunWorkerCompletedEventArgs.
Threading in C# from Joseph Albahari is quite good.
This page is quite a good summary of threading.
By the sound of it you probably don't need anything very complex - if you just start the task and then want to know when it has finished, you only need a few lines of code to create a new thread and get it to run your task. Then your UI thread can bumble along and check periodically if the task has completed.
Concurrent Programming on Windows is THE best book in the existence on the subject. Written by Joe Duffy, famous Microsoft Guru of multithreading. Everything you ever need to know and more, from the way Windows thread scheduler works to .NET Parallels Extensions Library.
Remember to create your delegates to update the UI so you don't get cross-threading issues and the UI doesn't appear to freeze/lockup
Also if you need a lot of notes/power points/etc etc
Might I suggest all the lecture notes from my undergrad
http://ist.psu.edu/courses/SP04/ist411/lectures.html
The best way for a total newcomer to threading is probably the threadpool. We'll probably need to know a little more about these parts to make more in depth recommendations
EDIT::
Since we now have a little more info, I'm going to stick with my previous answer, it looks like you have a loads of tasks which need doing, the best way to do a load of tasks is to add them to the threadpool and then just keep checking if they're done, if tasks need to be done in a specific order then you can simply add the next one as the previous one finishes. The threadpool really is rather good for this kind of thing and I see no reason not to use it in this case
Jason's link is a good article. Things you need to be aware of are that the UI can only be updated by the main UI thread, you will get cross threading exceptions if you try to do it in the worker thread. The BackgroundWorker control can help you there with the events, but you should also know about Control.Invoke (or Control.Begin/EndInvoke). This can be used to execute delegates in the context of the UI thread.
Also you should read up on the gotchas of accessing the same code/variables from different threads, some of these issues can lead to bugs that are intermittent and tricky to track down.
One point to note is that the volatile keyword only guarantees 'freshness' of variable access, for example, it guarantees that each read and write of the variable will be from main memory, and not from a thread or processor cache or other 'feature' of the memory model. It doesnt stop issues like a thread being interrupted by another thread during its read-update-write process (e.g. changing the variables value). This causes errors where the 2 threads have different (or the same) values for the variable, and can lead to things like values being lost, 2 threads having the same value for the variable when they should have different values, etc. You should use a lock/monitor (or other thread sync method, wait handles, interlockedincrement/decrement etc) to prevent these types of problems, which guarantee only one thread can access the variable. (Monitor also has the advantage that it implicitly performs volatile read/write)
And as someone else has noted, you also should try to avoid blocking your UI thread whilst waiting for background threads to complete, otherwise your UI will become unresponsive. You can do this by having your worker threads raise events that your UI subscribes to that indicate progress or completion.
Matt
Typemock have a new tool called Racer for helping with Multithreading issues. It’s a bit advanced but you can get help on their forum and in other online forums (one that strangely comes to mind is stackoverflow :-) )
I'm a newbie to multithreading as well, but I agree with Frank that a background worker is probably your best options. It works through event subscriptions. Here's the basics of how you used it.
First Instantiate a new background worker
Subscribed methods in your code to the background workers major events:
DoWork: This should contain whatever code that takes a long time to process
ProgressChanged: This is envoked whenever you call ReportProgress() from inside the method subscribed to DoWork
RunWorkerCompleted: Envoked when the DoWork method has completed
When you are ready to run your time consuming process you call the RunAsync() method of the background worker. This starts DoWork method on a separate thread, which can then report it's progress back through the ProgressChanged event. Once it completed RunWorkerComplete will be evoked.
The DoWork event method can also check if the user somehow requested that the process be canceled (CanceLAsync() was called)) by checking the value of the CancelPending property.

Categories

Resources