Does Python for .NET event handler execute in a worker thread - python-multithreading

I have a Python for .Net (2.7) script that subscribes to an event defined in a .NET assembly. When that event fires and my python-based event handler is called, is my handler executing in Python's main thread or in a worker thread?
...
def MyEventHandler(source, args):
print 'Received message: ' + args.Message
...
dotNetObject.SomeEvent += MyEventHandler
...
I figured it must be a worker thread but when I put this line of code in the handler:
print threading._active
it only reported the main thread:
{8920: <_MainThread(MainThread, started 8920)>}
How can I tell what thread a given line of Python is executing in?
UPDATE:
Okay, I found threading.current_thread(). Outside of my handler it returns:
<_MainThread(MainThread, started 7064)>
while inside my handler it returns
<_DummyThread(Dummy-1, started daemon 7916)>
So is a "DummyThread" a worker thread? Why didn't it show up in threading._active?
Thanks.

DummyThreads are worker threads and show up in this call:
threading.enumerate()
So, yes, the event handler is executing in a worker thread.

Related

In hiredis async, can event_base_dispatch(base) be called from a different thread?

This query is with respect to the example provided in hiredis
Can event_base_dispatch(base) be called from a different thread by creating pthread_create()?
It is a fact that event_base_dispatch() is a loop and it is a blocking call. My idea here is to send all my redis command from the parent thread by invoking redisAsyncCommand(), event base will be run in the other thread.
you need to use add enable_thread_safe_windows function before you create a event base.

Proper handling of child Greenlets

I am creating tasks by inheriting from Greenlet. I have a single parent task that calls start() on two children in its _run(). Elsewhere (it happens to be a systemd service) start() and join() are called.
The behavior seems correct. For example the use of a Queue with timeouts achieves the desired effect but I haven't found a good way to shutdown the children from say KeyboardInterrupt or by registering a callback to the parent task for SIGTERM. In the handler I would call child1.kill() and 'child2.kill()but only the first called seemed to raiseGreenletExit`.
I never call join() on the children and I'm not sure how I would do this properly. Am I misusing the library?
My error was that I was handling gevent.greenlet.GreenletExit in the child tasks. If you need to handle the exit you can catch and reraise this exception.

Suitable pattern for updating a progress bar from multiple threads (using TPL?)

I've been busy updating my brain with the TPL because I intend on using it for my new application (which uses .Net Framework 4.0). However I have some doubts that someone might clarify for me. Previously, I had a progress form which I would launch from the main (GUI) thread after I started the thread which needed to display its' progress. It looked something like this:
sortThread = New Thread(AddressOf _Sorter.Sort())
_ProgressForm = New FrmProgress()
_Sorter.ProgressForm = _ProgressForm
sortThread.Start()
progressForm.ShowDialog()
Basically it would initialize the thread, initialize a FrmProgress form object and assign it to the Sorter object which would then update the progress form (which contained a progress bar and some labels) from its Sort() sub on the separate thread. Updating these control properties was achieved by checking the InvokeRequired property of the FrmProgress form and if needed it would then use the Invoke() method of the control that was to be updated... ex:
Public Sub IncrementProgressBar(x As Integer)
If Me.InvokeRequired Then
pb_MainProgressBar.Invoke(Sub() IncrementProgressBar(x))
Else
pb_MainProgressBar.Increment(x)
End If
End Sub
Now I am interested in using TPL to launch separate worker threads (multiple) that may want to update the progress bar. Should I use the same pattern or should I consider accessing a public TaskScheduler.FromCurrentSynchronizationContext context that was obtained in the main GUI thread? In both cases I suppose I should provide some kind of locking mechanism on the form (SyncLock?)
Invoke should be sufficient, as you are doing. If two different threads try to invoke in parallel the first one will execute first, then the second when the UI thread becomes free. The UI thread cannot service two invokes simultaneously - they are naturally handled in FIFO sequence so there is no issue with thread safety. Any number of threads can invoke on the main thread without worrying about each other or using any additional locking mechanism.
Note, however, that any thread calling Invoke will block until the main thread can service the call. If you, for example, had many threads invoking heavy code at the same time then your various threads would block on the invoke calls until they got their kick at the can, so to speak. If you use BeginInvoke then the calling thread will simply continue executing and the invoked method will be placed in the UI thread's queue (which it will service as soon as it can).

.Net Asynchronous Delegate Abortion

Background: My application is used to execute tests using Selenium RC servers, and occasionally I'm running into a problem when my call to a Selenium command doesn't return the response from the RC server - it then ends up blocking the thread that is executing the test.
Sample Code:
Private Delegate Function DoCommand_Delegate(ByVal command As String, ByVal args() As String) As String
...
asyncCommand = New DoCommand_Delegate(AddressOf server.DoCommand)
asyncResult = asyncCommand.BeginInvoke(command, args, Nothing, Nothing)
Try
... (I have it use the AsyncWaitHandle to wait for periods of 10 seconds up to two minutes. At the end of each period it runs some checks for common problems that block Selenium from returning a response (modal dialogs) - I don't think that part is relevant to this question, it's just necessary.)
Finally
result = asyncCommand.EndInvoke(asyncResult)
...
At the time EndInvoke is called, the worker delegate has either already finished or needs to be aborted. Most of the time it already has a response so it works just fine, but on rare occasion Selenium RC's DoCommand doesn't return, so the thread sits there locked.
Finally, my question: is there a resource-friendly way to abort the executing delegate, or do I need to convert it to use a manually controlled thread that can be aborted and disposed?
Note: This is not a question regarding Selenium, just proper multithreading.
Note 2: I've considered doing the following in the Finally before calling EndInvoke:
If Not asyncResult.IsCompleted Then asyncResult.AsyncWaitHandle.Close()
... But I don't know if that would actually work correctly, or what damage that could cause.
There is no way to do the following at the same time:
Abort/kill a thread non-cooperatively
Without destroying all state associated with it (AppDomain/process)
Implies: Either terminate cooperatively (not possible here) or kill the process (AppDomain not enough because native state is involved) or don't kill the thread.
You could just not kill the thread and leave it there hanging. The rest of your program (the remaining tests) can continue to execute.
I'd not be happy to see this in production but for a test suite this could be ok (assuming the hang cannot be fixed).
Why can't a thread be aborted? This has been covered a number of times on Stack Overflow already.

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

I am writing a filewatcher windows application which will look for changes in a specified folder and then logs the details in a txt file.
I followed exactly what is mentioned in this article below
http://www.codeproject.com/KB/dotnet/folderwatcher.aspx
When I hit F5 from my application and then create or modify a file in the folder that is being watched it throws the below mentioned error.
Please help
Cross-thread operation not valid: Control 'txtFolderActivity' accessed from a thread other than the thread it was created on.
You have to use the Invoke method on the form e.g. with an anonymous delegate to make your changes in reaction to the event.
The event handler is raised with another thread. This 2nd thread cannot access controls in your form. It has to "Invoke" them to let the thread do all control work that initially created them.
Instead of:
myForm.Control1.Text = "newText";
you have to write:
myForm.Invoke(new Action(
delegate()
{
myForm.Control1.Text = "newText";
}));
You are trying to update the UI from a non-UI thread. UI has a thread affinity and can only be updated from a thread that created it. If you're using WinForms, check out How to: make thread-safe calls to Windows Forms Controls MSDN article. Basically you will need to update the UI via Control.Invoke method. For WPF, you need to use DispatcherObject.
Basically you must have two threads in your application, at least, and the thread that your control logic is on is different, so you get this error, as the controls are not threadsafe.
This is to protect you from problems that could be caused by multiple threads changing the same control at the same time.
You can find considerably more detail by looking here:
http://msdn.microsoft.com/en-us/library/ms171728%28VS.80%29.aspx