I developed a class (in C#) for sending and receiving messages over network. It creates a new thread (listener thread) which waits till a new message arrives then raises an event.
The problem is the event is raised in the listener thread and when I want to use this class in a wpf application, a run-time error occurs trying to handle the event
The error is:The calling thread cannot access this object because a different thread owns it.
Is there any proper way to deal with this situation when the event raises in the mentioned class?
You've got to be on the UI thread to update UI objects. You can use the window's Dispatcher to execute code there:
this.Dispatcher.Invoke(new Action(() =>
{
// Code that updates UI here
}));
BackgroundWorker explicitly supports marshaling to the UI thread. You have to use it though, call its ReportProgress() method. While optimized for reporting progress, you don't have to use it for that. There's an overload that accepts an object, you can pass anything you want. The event handler gets it as the e.UserState value. From there, you could use that object directly or use it to re-raise another set of events.
Do beware thread-safety requirements for that object. The worker keeps running and is not in any way synchronized with the execution of the ProgressChanged event handler. So it should no longer update the object. Best to create a new instance of it after calling ReportProgress().
Related
I'm working on an Outlook Addin, and I have to process a large amount of items. This takes quite a lot of time, and I therefore tried to have the processing running in a different thread (using Task.Factory.StartNew). However, that results in Outlook randomly crashing.
I'm using Redemption to work with MAPITable, in order to reduce workload and load only relevant data.
I've tried initializing my RDOSession from both my main thread, and my worker thread.
I've tried getting the MAPIFolders on the main thread, and working with only the MAPITable on the worker thread
Currently, the only thing that works for me is running all my logic on the main thread (in the button click event), however that locks Outlook's user interface for a long period of time, which is unacceptable from a user's point of view.
Does anyone have some pointer on how to work with background threads from within an Outlook Addin?
Having similar code in my project I would suggest the following:
Create new thread using the Thread class and set it apartment to STA.
Loggin to session using "session.Logon("profileName", NoMail: true, NewSession: false);" and not using MAPIOBJECT. I found it has better performance than using MAPIOBJECT, my guess is it still marshal some calls back to the main thread as MAPIOBJECT was created on the main thread.
Use "Marshal.ReleaseComObject" on each and every COM object you use as soon as you are done with them. This is probably what causing the instability as Outlook really doesn't like when it's object are left too long. For example this line of code "var table = rdoFolder.Items.MAPITable;" create two COM objects: RDOItems and MAPITable, both of them must be released so you need to split this line to hold reference to RDOItems object.
Call GC.Collect and Application.DoEvents because if you don't call Marshal.ReleaseComObject on all COM object the finalizer will try to release them and will hang because the COM objects were created on thread that don't pump message loop and it's finalizer method must run on the thread that created them.
If you can, fire a secondary process and do this loop in the separate process. This will make maximum separation between the UI and your background work.
What was the problem using RDO objects in a secondary thread? As long as RDOSession is created on the secondary thread, MAPI should be properly initialized.
Also, TaskFactory uses a thread pool, you'd be better off using an explicit Thread class, o at least make sure that RDOSession is not shared between different threads - MAPI must be initialized on each thread.
Is it equivalent/better to work
with the Event module on Event type
or with Observable on the publish property of an event
Functionally it seems equivalent, and I guess the difference is 'semantic' :
Are we inside the boundary where it makes sense to have access to the internal state of
the event ?
Or are we considering this event interface as a passive source from which a stream was exposed to us
Is that the correct thinking ?
The main difference between Event and Observable is in how they handle state and un-subscription.
Event functions attach to the source event and do not give you any way to unsubscribe. If you use stateful combinators (like Event.scan) and then attach multiple observers to the resulting event, then they will all see the same state.
Observable functions construct "specification" of the processing pipeline. When you attach a handler to IObservable value, you get back an IDisposable that can be used to remove all handlers. Each handler attached to IObservable will get a new state (because the runtime creates a new processing chain according to the "specification").
In practice, the main difference is in the statfullness - if you want to share state, you can use the Event module - implementing the same using Observable is possible but harder.
If you're using events inside async, then you should use Observable and AwaitObservable (instead of built-in AwaitEvent), because using event combinators will leak memory - it will attach event handlers that are never removed.
In my app, I read/parse data that takes some time. While that process is going on I want to display a message on screen indicating the process going on. I beileve I got to use Thread for it, but don't get an idea how to use and implement it.The calling method may throw exception or so.
Any idea/tip on how to achieve the task. Any help is highly appreciated.
Thanks
I'll assume that you're using .Net.
You should use the BackgroundWorker component.
Perform your operation in its DoWork event (which runs on a background thread), call ReportProgress to post messages for the UI, and handle ProgressChanged and RunWorkerCompleted to update the UI.
I have an object that is updated from a polling loop on a thread. This object fires particular events when data changes, etc.
I'm trying to use this object in conjunction with a windows form, where I create event handlers on the form to update the UI. Of course, this causes cross-thread operation exceptions if I try to manipulate the UI directly in these handlers.
I can get it to work by going through the standard procedure of checking InvokeRequired, using a delegate, blah blah blah. But I want to publish this object as a library, and I don't want end-users to have to worry about all that.
I want my object to somehow take care of synchronizing those event callbacks with the form so that end-users can manipulate the UI elements in those handlers worry-free.
Is there a way to do this??
If your object is always related to a single form, there is a simple trick indeed. The important fact here is, that you instanciate your object from the thread you like to affect the form later.
The trick is to instanciate a simple Control (new Control()) in your object in the constructor. When you perform logic on your form, use the Invoke/BeginInvoke methods on this simple control, to dispatch the action to the correct calling thread. So you have the dispatching logic directly in your object and there is no need for other users of your object to take care about this.
I wish to launch a separate thread for handling window messages (via a blocking GetMessage loop), but still create the windows in the initial thread, afterward.
Within the separate thread, as soon as it launches, I am calling PeekMessage with PM_NOREMOVE to ensure a message queue exists (is this necessary?), followed by..
AttachThreadInput(initial thread id,GetCurrentThreadId(),true)
..before finally entering the message loop
I am not yet using a mutex or cs to ensure this is happening in time, but am merely using a Sleep statement in my initial thread for the sake of simplicity.
Regardless, window messages do not appear to be intercepted by the separate thread.
I am a little unsure as to whether I am doing this correctly, and would appreciate any possible guidance. Both threads are in the same process
Thank you all
That's not what AttachThreadInput does. Even after you attach your input queue to another thread, Windows still have thread affinity. Messages in the queue for a given window can only be removed from the queue by that window's thread.
What AttachTheadInput does is to make two threads share an input queue. This allows them to query information about the input state and know that the other thread will get the same answer for the same query. For instance, one thread could call GetAsyncKeyState and know that the answer reflected the key state for the other thread.
It allows two or more threads to have the same relationship to the input queue and each other as processes had in Windows 3x. This is the reason that this API exists; so that complex multiprocess applications could be ported from Win 3x to Win95/WinNT.
It seems the best way to instigate window creation from the main thread, while having messages for them handled in a separate, looping thread is to use a custom message, that can be sent to the separate thread - Thus allowing it to create the window, but still allowing that action to be invoked from the initial thread:
1) Allocate a custom message, and create a structure to hold the window initialisation parameters:
message_create_window = WM_USER + 0;
class Message_create_window{
Message_create_window(...);
};
2) Instead of calling CreateWindow(Ex), use something similiar to the following, passing in the relavant window creation parameters:
PostThreadMessage(
thread.id,
message_create_window,
new Message_create_window(...),
0
);
3) Handle the custom message in the message pump of your ui handling thread, extract the creation parameters, & free afterwards:
MSG msg;
GetMessage(&msg,0,0,0);
...
switch(msg->message){
...
case message_create_window:{
Message_create_window *data=msg->wParam;
CreateWindowEx(data->...);
delete data;
}break;
...
This does, however, have the following side-effects:
The window will be created asynchronously. If it is required that the initial thread block until the window is created (or, indeed, that the window's existence can ever be asserted) then a thread synchronisation tool must be used (such as an event)
Care should be taken when interacting with the window (it is a multithreaded application, after all)
If there are any major holes in this answer, or this seems like a terrible approach, please correct me.
(This is still my question, & I am trying to find the best way to accomplish this)