ceyun
ceyun

Reputation: 381

Can I interrupt a method while this method is working?

Can we interrupt a method while its working?Because I have a method that in a thread and I have to interrupt that method when button click. How can I do that?

I tried Abort() method but its not working. Because Abort() is a method which don't have any garanty behavior. I mean if we use that method, we don't sure about method termination.

I have just a method name like DoSomething() because I use a DLL which is written in C++. Hence I dont have a source code of method. And if I click a button, this method must be terminated

Please give me some advice about it.

Upvotes: 0

Views: 3150

Answers (3)

ceyun
ceyun

Reputation: 381

I have solved the problem. If someone has problem like that, maybe it can find an answer in following pages

I got some information about my question in below link

Abort call to unmanaged DLL

I found an example about my solving way

Using kernel32 CreateThread/TerminateThread inside Azure Worker Role

And you can use this page. This page contains a lot of code part about PInvoke.

http://www.pinvoke.net/

Upvotes: 0

pid
pid

Reputation: 11607

If you have access to the method implement a flag to abort it and code your way around the problem. This is a conceptual pseudo-C# example of what I'd do:

private bool aborted = false;

public ResultClass Method()
{
    for (i = 0; i < int.MaxValue && !aborted; i++)
    {
      // ...
    }

    if (aborted)
    {
        return null;
    }

    return new ResultClass(...);
}

public void Abort()
{
    aborted = true;
}

This might look like a lot of code but it is cleaner, you can clean-up and handle stuff as you need it. Aborting a thread, instead, is a messy affair and can only happen when the thread hits a WaitSleepJoin state.

If you really need to abort, at least do something like this:

try {
    // abortable code
}
finally
{
    // clean-up resources
}

Upvotes: 1

man_luck
man_luck

Reputation: 1666

you can use Abort on a thread and not on a method. If you want to interrupt a method use return.

Upvotes: 0

Related Questions