0

I have this existing code that doesn't properly clear the thread on dispose. First off, to start the thread that waits for incoming signals and process them:

public void StartTheWholeThing(){
    manualResetEvent = new ManualResetEvent();
    thread = new Thread(StartRunning);
    thread.start();
    manualResetEvent.Set();
}

public void StartRunning()
    {
        //Listen for foreground changes 
        hhook = SetWinEventHook(EventSystemForeground, EventSystemForeground, IntPtr.Zero,
                ProcessDelegate, 0, 0, WineventOutofcontext);

        // Thread state
        manualResetEvent.WaitOne();

        //  mesage loop that SetWinEventHook requires
        Application.Run();
    }

private void ProcessDelegate(){
    //Do something
}

Now we want to properly close the thread.

public void StopRunning(){
    manualResetEvent.Reset();
    thread.Abort();  // IS THIS THE CORRECT MANNER?
}

Thread.Abort() seems a rough way to close the thread. Is there a more clean way to start/stop threads in combination with the SetWinEventHook?

hasdrubal
  • 1,024
  • 14
  • 30
  • It is not clear that you need a separate thread at all. You do, however, need to pass the return value `hhook` to [`UnhookWinEvent()`](https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-unhookwinevent) when you no longer need the hook. – Matthew Watson Oct 22 '18 at 08:05
  • ah, yeap. forgot to post that line of unhook code. but it's in there. Sharp. If ProcessDelegate() takes a long time to run and I want responsive UI, I believe I do need to run this on a different thread, correct? – hasdrubal Oct 22 '18 at 08:07
  • https://stackoverflow.com/questions/4359910/is-it-possible-to-abort-a-task-like-aborting-a-thread-thread-abort-method – go.. Oct 22 '18 at 08:12
  • `If ProcessDelegate() takes a long time to run and I want responsive UI, I believe I do need to run this on a different thread, correct? ` Well you are still running `ProcessDelegate()` on the same thread as the UI, since you called `Application.Run()` from that same thread! You'd be better off starting a task inside `ProcessDelegate()` to handle each event as it comes in. – Matthew Watson Oct 22 '18 at 08:29
  • @SinanBARAN So the question confirms my hunch that abort is controversial. But in this case not that helpful. I need to know how to properly setup and dispose this message loop with SetWinHookEvent. – hasdrubal Oct 22 '18 at 08:42
  • @MatthewWatson How would I properly setup so that ProcessDelegate() gets handled by it's own thread? – hasdrubal Oct 22 '18 at 08:42
  • Inside `ProcessDelegate()` you'd just do `Task.Run(someMethodToHandleIt);` – Matthew Watson Oct 22 '18 at 08:48
  • So then the initial signal goes to the main UI thread, which then starts a work thread right? That might actually work. – hasdrubal Oct 23 '18 at 08:42

0 Answers0