Get the mainThread to run again? - winforms

Hi,
I have a winform application that is hosting a WCF Service(NamedPipes). When reciving a call a event will be triggered and then a form will be created and opened. The problem is that I get the followin exception
ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment.
When creating a System.Windows.Forms.WebBrowser in the winforms InitializeComponent method?
I Supose that another thread is running the even(working thread), how can I get the main thread to run the event?
I do not have any winform open at the time so I canĀ“t use InvokeRequired.
BestRegards
Edit1 : Pleas not that I am using
[STAThread]
public static void Main(string[] args)
{
Application.Run(_instance);
}

These kind of calls are made on thread pool threads. They are not suitable to display any UI. You'll need to create your own thread of the right flavor:
var t = new Thread(() => {
Application.Run(new Form1());
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
There are other practical problems you'll be battling with this, you can't just pop up a window without the user participating. Typical mishaps are the user accidentally closing it without even seeing it or the window disappearing behind the window that the user is working with. If you already have a user interface then be sure to use Control.BeginInvoke() to let the main thread display the window. Consider the soft touch with a NotifyIcon, displaying a balloon in the tray notification area to alert the user.

That WCF call is most likely coming in on a thread other than the main UI thread. All UI controls including ActiveX ones must be created and accessed from the UI thread and only the UI thread. The error you are getting is indicating that the creating thread is not even in a Single Thread Apartment (STA) which is also a requirement.
To get the code executing on the main UI thread use the Control.Invoke method. It will marshal the execution of a delegate onto the thread hosting the target Control or Form.
If you do not have a reference to a Control or Form immediately available then you will need to create one. You may have to create a thread that runs a message loop as well. This can be done with Application.Run. It is simple enough to create a hidden Form that could be used to call Invoke.
Here is what it might look like.
void SomeMethodExecutingOnThreadPool()
{
var form = null;
var mre = new ManualResetEvent(false);
// Create the UI thread.
new Thread(
() =>
{
form = new Form();
form.Load +=
(sender, args) =>
{
mre.Set();
}
Application.Run(form);
}).Start();
// Wait for the UI thread to initialize.
mre.WaitOne();
// You can now call Invoke.
form.Invoke(/* ... */);
}

My solution is to create a dummy winform on startup and when I need the main UI thread I will use invoke on this dummyform.
It will use some more resourse but I dont see a simpler way of doing it.

Related

How to tell Dispatcher is initialized and running?

In my console app I've been trying to start an STA thread and show a WPF window. I've succeeded showing the window, but I had issues with a library using Dispatcher (System.Reactive.Windows.Threading to be precised). I've fixed my problems using code from this doc - what I was missing was calling System.Windows.Threading.Dispatcher.Run() in the right moment.
But after reading this article carefully (and others) and examining Dispatcher's API I still don't know: how to tell WPF Dispatcher is correctly initialized and running? It'd be very useful for libraries requiring Dispatcher, if they could check it.
-- EDIT --
// Extending my question after #Peter Duniho remarks
Having C# console application I wanted to create a WPF window, where I'll observe, on Dispatcher, some data. The full code is here
So I have my program, where Main class looks like that:
static void Main(string[] args)
{
var observable = Observable
.Interval(TimeSpan.FromMilliseconds(500))
.TakeWhile(counter => counter < 10);
var thread = new Thread(() =>
{
new TestWindow(observable);
Dispatcher.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
Console.ReadKey();
}
I create here an observable with Interval operator, which ticks every 500 milliseconds, and I pass it to a TestWindow (code below) which I run on a separate thread. After 10 ticks I end the observable sequence.
TestWindow class:
public class TestWindow : Window
{
public TestWindow(IObservable<long> observable)
{
var isDispatcherInitialized = false;
Dispatcher.Invoke(() => isDispatcherInitialized = true, DispatcherPriority.ApplicationIdle);
if (!isDispatcherInitialized)
throw new ApplicationException("Dispatcher not initialized");
observable
.ObserveOnDispatcher()
.Window(TimeSpan.FromMilliseconds(600))
.Subscribe(_ => Console.WriteLine($"OnNext, observed on dispatcher with Window operator"));
}
}
In TestWindow I observe my observable on Dispatcher (ObserveOnDispatcher()), and I use Window operator.
PROBLEM with that code (tested on .NET Framework and on .NET Core 3.0 preview):
if I don't call Dispatcher.Run(); when starting STA thread, the validation where I call Dispatcher.Invoke() will be passed, but ObserveOnDispatcher() won't work correctly - subscription never stops, and the message: "OnNext, observed on dispatcher with Window operator" goes forever.
That's why I was wondering if I could detect Dispatcher's state.
It would be helpful if you would elaborate on this statement:
It'd be very useful for libraries requiring Dispatcher, if they could check it.
That is, why would it be useful?
For one, if you are using a third-party library (such as the Reactive Extensions (Rx) for .NET you mentioned, how would you knowing how to check for the dispatcher state help that library?
For another, what scenario doesn't work for you? Lacking a specific problem to solve, your question is fairly open-ended. It's not clear what type of answer would actually address your question.
That said, two things come to mind:
If you want to know if a dispatcher has been created for a given thread, you should call System.Windows.Threading.Dispatcher.FromThread(System.Threading.Thread.CurrentThread); This will return null if not dispatcher has been created yet for that thread, or a reference to the dispatcher if it has been.
If you want to know that the dispatcher has completed initialization and is ready to dispatch things, it seems to me that the easiest thing to do is ask it to dispatch something, and when it does, it's ready. Using an overload of one of the invoking methods (BeginInvoke(), Invoke(), or InvokeAsync()) that takes a DispatcherPriority value, you can get fine-grained information regarding just what level of initialization has happened. For example, if you pass DispatcherPriority.Normal or DispatcherPriority.Send, when your delegate is invoked you'll know that the dispatcher is running. But if you pass DispatcherPriority.ApplicationIdle or DispatcherPriority.SystemIdle, you'll know that not only is the dispatcher running, but it's cleared its backlog of initial events to dispatch and the application is sitting waiting for user input.

How do I run code in a thread that called a parameterless Application.Run()?

I want to render a chart with the DevExpress ChartControl via the WiForm DrawToBitmap() function on a separate thread.
I try something like:
Form yourForm;
Thread thread = new Thread( () =>
{
yourForm = new HiddenForm();
Application.Run(yourForm);
});
thread.ApartmentState = ApartmentState.STA;
thread.Start();
yourForm.Invoke(chartRenderingFunction)
And simple make sure the Hidden never actually gets displayed. However, I don't need that hidden form, and there is a parameterless form of Application.Run(). However, if I run that, it doesn't return. So my question is once I call Application.Run() inside a thread, how do I inject code in it?
Well, you actually really do need that hidden window. The only way to get code to run on that thread. Somebody must call PostMessage() and that requires a window handle. Your Invoke() call makes that call. You really should use BeginInvoke() instead, there's no point in starting a thread if you are going to wait for the call to complete.
Using Application.Run(yourForm) is going to make the window visible. You can stop it from becoming visible by overriding the SetVisibleCore() method in your HiddenForm class:
protected override void SetVisibleCore(bool value) {
if (!this.IsHandleCreated) {
CreateHandle();
value = false;
ThreadReady.Set();
}
base.SetVisibleCore(value);
}
The CreateHandle() call is necessary to make sure that the window is created so it can process the PostMessage() notifications. Also note the added AutoResetEvent (ThreadReady), you are going to have to call ThreadReady.WaitOne() after calling the thread's Start() method to ensure that your BeginInvoke() call is going to work. Dispose the form to get the thread to exit or call Application.Exit().
Last but not least, be very careful with using non-trivial controls on that thread. A chart control certainly is not indicated. You'll have long-lasting problems if that control uses the SystemEvents class for example. Your worker thread will get it to raise events on that worker thread. But it won't be around anymore after the chart is printed. You'll now get the events fired on an arbitrary threadpool thread, very nasty. A deadlock is a common mishap, particularly apt to trigger when locking the workstation.

WPF LifeCyle in an Add-in

I've created an add-in, which call via Reflection, a WPF Class Library.
Since this is a class library, I had to instanciate manually a new System.Windows.Application().
Then, the class constructor (the one called via reflection) create a window, and Show() (with Dispatcher.Run() to avoid the window to close immediately) or ShowDialog().
Since my application is into an add-in, Application is still alive.
Therefore, I can instanciate this only once.
On the first launch (when Application is instanciated), the Application.Current.Dispatcher is Running.
But on the second launch, I firured out that the Application.Current.Dispatcher was Stopped.
I never call InvokeShutdown() so I don't understand when the Dispatcher is stopped.
When I launch this a second time, Application is already instanciated (it's normal) but Dispatcher stopped.
Any idea ?
Thanks !
Edit : In my Add-in, I've tried 2 ways :
First way :
foreach (Type type in ass2_l.GetTypes())
{
if (type.Name == "Loader")
{
object obj_l = Activator.CreateInstance(type);
BindingFlags bf_l = BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
object[] argList_l = new object[1];
argList_l[0] = "ok";
type.InvokeMember("Load", bf_l, null, obj_l, argList_l);
}
}
When I call directly the dll from the add-in, Application.Current.Dispatcher is in Background State, with name "VSTA_Main".
When I launch a second time, Dispatcher is still in background state.
Second way :
t_m = new Thread(loadDll);
t_m.SetApartmentState(ApartmentState.STA);
t_m.Start();
loadDll actually contain the same code of the "first way" code.
When I launch this part for the first time, the Dispatcher is Running, and all is perfectly normal.
When launched the second time, Dispatcher is stopped.
EDIT 2 :
The problem is in the second way.
When loadDll is finished and then I click again on my add-in button, t_m is stopped and creating another one don't resolve the problem since the Dispatcher ManagedThreadId has the old t_m ManagerThreadId :/
EDIT 3 :
The problem is definately not caused by the Add-in.
If you Just create a program that launch a thread everytime you click on a button.
The thread try to instanciate a DLL WPF Class Library (by reflection), and if you click a second time on this button (calling another thread), as the Dispatcher is still "linked" to the old thread, the Dispatcher is "stopped" (like the old thread)
In ThisAddin.Startup event handler put this code:
private void ThisAddInStartup(object sender, EventArgs e)
{
if (System.Windows.Application.Current == null)
new System.Windows.Application();
System.Windows.Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown
}
That should sort it out, it has worked fine for me in the past..
Finally, I solved the problem using an infinite loop to stay the thread in running state, with AutoResetEvent / ManualResetEvent to start/stop the thread...
As the thread never finish (and call a method which load the WPF UI dll when he receive the start event), we never stop the thread (until we stop the Add-in), and the dispatcher is never stopped too.
BTW, thank you for all your answers :)

Question about making Asynchronous call in C# (WPF) to COM object

Sorry to ask such a basic question but I seem to have a brain freeze on this one! I'm calling a COM (ATL) object from my WPF project. The COM method might take a long time to complete. I thought I'd try and call it asychronously. I have a few demo lines that show the problem.
private void checkBox1_Checked(object sender, RoutedEventArgs e)
{
//DoSomeWork();
AsyncDoWork caller = new AsyncDoWork(DoSomeWork);
IAsyncResult result = caller.BeginInvoke(null, null);
}
private delegate void AsyncDoWork();
private void DoSomeWork()
{
_Server.DoWork();
}
The ATL method DoWork is very exciting. It is:
STDMETHODIMP CSimpleObject::DoWork(void)
{
Sleep(5000);
return S_OK;
}
I had expectations that running this way would result in the checkbox being checked right away (instead of in 5 seconds) and me being able to move the WPF gui around the screen. I can't - for 5 seconds.
What am I doing wrong? I'm sure it's something pretty simple. Delegate signature wrong?
Thanks.
I'm sure you're right about the call to your ATL code getting marshaled to the GUI thread because the ATL code is STA, thereby blocking your GUI thread.
Two solutions:
Rearchitect the ATL portion to be MTA, which may not be feasible, or
Leave the ATL as STA but initially construct the COM object in a thread created for that purpose so it will get a different apartment.
A WPF application actually runs just fine with multiple UI threads, as long as each UI thread has manages its own part of the UI, and the parts are separated by HwndSource. In other words, the second thread that runs part of the UI implements a Win32 HWND which is then embedded in the portion of the UI run by the main thread.
If your COM object isn't itself a GUI object, then it should be very easy to construct it in a separate worker thread and leave it there. Since it is a STA object, all calls will be marshaled to the other thread.
BeginInvoke is still going to execute your call on the same thread, just asynchronously*. You can either create a new Thread object:
Thread comthread = new Thread(new ThreadStart(delegate() { DoSomeWork(); }));
comthread.Start();
or try out .Net 4's new Task library:
Task.Factory.StartNew(() =>
{
DoSomeWork();
});
which are essentially the same thing.**
*A delegate type's BeginInvoke method executes on the same thread as the caller, but in the background. I'm not sure if there are rules regarding what gets executed when, but it's certainly not in the order you want. However, asynchronous methods like BeginRead execute on a special thread separate from the main one.
**There is a slight difference - the Thread method will always create a new Thread object, whereas the Task system has a pool of threads to work with, which is in theory more efficient.
I have done some more thinking and testing about this. There is nothing wrong with the C# code. If the ATL object is an STA object (as it was in my case), it will be called on the main thread, regardless of attempts by the C# code to call it on a worker thread. Changing the ATL object to an MTA object makes it possible to to call it asynchronously.

Prevent UI from freezing without additional threads

What solutions do I have if I want to prevent the UI from freezing while I deserialize a large number of UI elements in WPF? I'm getting errors complainig that the objects belong on the UI Thread when I'm trying to load them in another thread. So, what options do I have to prevent the Vista "Program not responding" error while I'm loading my UI data? Can I rely on a single-threaded solution, or am I missing something regarding perhaps multiple UI Threads?
If you only use a single thread then the UI will freeze while you do any amount of processing.
If you use a BackgroundWorker thread you'll have more control over what happens & when.
To update the UI you need to use Dispatcher.Invoke from your background thread to marshal the call across the thread boundary.
Dispatcher.Invoke(DispatcherPriority.Background,
new Action(() => this.TextBlock.Text = "Processing");
You can turn the flow of control on its head using DispatcherFrames, allowing a deserialization to proceed on the UI thread in the background.
First you need a way to get control periodically during deserialization. No matter what deserializer you are using, it will have to call property sets on your objects, so you can usually add code to the property setters. Alternatively you could modify the deserializer. In any case, make sure your code is called frequently enough
Each time you receive control, all you need to do is:
Create a DispatcherFrame
Queue an event to the dispatcher using BeginInvoke that sets Continue=false on the frame
Use PushFrame to start the frame running on the Dispatcher
In addition, when calling the deserializer itself make sure you do it from Dispatcher.BeginInvoke, or that your calling code doesn't hold any locks etc.
Here's how it would look:
public partial class MyWindow
{
SomeDeserializer _deserializer = new SomeDeserializer();
byte[] _sourceData;
object _deserializedObject;
...
void LoadButton_Click(...)
{
Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
_deserializedObject = _deserializer.DeserializeObject(_sourceData);
}));
}
}
public class OneOfTheObjectsBeingDeserializedFrequently
{
...
public string SomePropertyThatIsFrequentlySet
{
get { ... }
set { ...; BackgroundThreadingSolution.DoEvents(); }
}
}
public class BackgroundThreadingSolution
{
[ThreadLocal]
static DateTime _nextDispatchTime;
public static void DoEvents()
{
// Limit dispatcher queue running to once every 200ms
var now = DateTime.Now;
if(now < _nextDispatchTime) return;
_nextDispatchTime = now.AddMilliseconds(200);
// Run the dispatcher for everything over background priority
var frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
frame.Continue = false;
}));
Dispatcher.PushFrame(frame);
}
}
Checking DateTime.Now in DoEvents() isn't actually required for this technique to work, but will improve performance if SomeProperty is set very frequently during deserialization.
Edit: Right after I wrote this I realized there is an easier way to implement the DoEvents method. Instead of using DispatcherFrame, simply use Dispatcher.Invoke with an empty action:
public static void DoEvents()
{
// Limit dispatcher queue running to once every 200ms
var now = DateTime.Now;
if(now < _nextDispatchTime) return;
_nextDispatchTime = now.AddMilliseconds(200);
// Run the dispatcher for everything over background priority
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new Action(() => {}));
}
Here is a wonderful blog posting from Dwane Need that discusses all the available options for working with UI elements amongst multiple threads.
You really haven't given enough detail to give a good prescription. For example, why are you creating UI elements yourself at all instead of using databinding? You might have a good reason, but without more details it's hard to give good advice. As another example of detail that would be useful, are you looking to build complex deeply nested control hierarchies for each piece of data or do you just need to draw a simple shape?
I had a similar problem with my panel which was moving its items. The UI was freezing because I was using a DispatcherTimer at priority Loaded. The problem is gone as soon as I changed it to DispatcherPriority.Input.
You can still make your long processing in a separate thread, but when finished you have to synchronize with the UI thread by calling Dispatcher.BeginInvoke(your_UI_action_here)
Recommendations from the OldNewThing blog.
It is best if you do go the threaded route, to have one GUI thread and spawn your work load off to another thread that when finishes reports back to the main GUI thread that its done. The reason for this is because you will not get into thread issues with your GUI interface.
So One GUI Thread
Many worker threads that do the work.
If any of your threads do hang the user is in direct control over your application can can close down the thread without effecting his experience with the application interface. This will make him happy because your user will feel in control other than him constantly click THAT STOP BUTTON AND IT WONT STOP SEARCHING.
Try freezing your UIElements. Frozen objects can be passed between threads without encountering an InvalidOperationException, so you deserialize them & freeze them on a background thread before using them on your UI thread.
Alternatively, consider dispatching the individual deserializations back to the UI thread at background priority. This isn't optimal, since the UI thread still has to do all of the work to deserialize these objects and there's some overhead added by dispatching them as individual tasks, but at least you won't block the UI - higher priority events like input will be able to be interspersed with your lower priority deserialization work.

Resources