Search code examples
c#wpfmultithreadingsingle-threaded

Is it possible to stop single threaded execution of code from UI?


In my solution I got a user interface where some word automation is started by a buttonclick (lets call that button wordStart). I want to break this word automation with another buttonclick (lets call that button wordBreak).

However when I click the wordStart the user interface freezes while doing the work and it's not possible for me to click the wordBreak button. I'm still a bit new to programming so for me this must be because the application is single threaded or atleast I could solve it with multithreading.

So this is a 2 in 1 question. 1. Is it possible to stop the execution of code with a single threaded application? 2. How do I stop the execution of code?

For question number 2 I looked a bit around the internet and found these methods which I think will work, but other suggestions are welcome:

Application.Exit

Application.Shutdown

Environment.Exit

EDIT: As I thought this should be done with multi threading. I don't have that much experience with that so I've added this code to the question if anyone would like to help me out here. In the meantime I will look for a solution to this myself.

    private void generateButton_Click(object sender, EventArgs e)
    {
        //Thread or backgroundworker should handle this event?
        commandsChosed(); //Event to be throwed - this starts the word automation
    }

    private void stopButton_Click(object sender, EventArgs e)
    {
        //Stop/pause the working thread
    }

Solution

  • No, by using only a single thread it gets blocked until the execution is finished. If you want to be able to cancel/pause it, you need to use another thread for the operation. For instance you can use BackgroundWorker.