如何取消执行非托管C++外部程序的任务

5

我正在尝试修复C#异步代码,以启动在未经管理的C++例程中执行的可取消操作的外部dll。

如果用户委托调用外部非托管C++例程,是否有一种方法可以使用传递给任务的取消令牌取消任务?

据我所知,任务取消涉及用户委托和请求取消的代码之间的协作。成功的取消涉及请求代码调用CancellationTokenSource.Cancel方法,并且用户委托通过简单地从委托返回或使用CancellationToken.ThrowIfCancellationRequested方法抛出OperationCanceledException,及时终止操作,当他注意到取消请求已被发出(通过轮询CancellationToken.IsCancellationRequested方法)。 (参见http://msdn.microsoft.com/en-us/library/dd997396%28v=vs.110%29.aspx

这两种方式都涉及由用户委托执行的非托管C++例程通过将CancellationToken作为参数接收并定期调用其IsCancellationRequested和/或ThrowIfCancellationRequested方法来合作。

从非托管外部C++例程中是否可能实现这一点?

如果不行,是否有一种方法可以在请求代码请求取消时强制终止执行用户委托(执行非托管C++例程)的任务?

以下是我试图修复的混合C# / C++Cli /非托管C++代码的示例(摘录):

FrmDemo.cs:-------------------------------------------------------------------------

public class FrmDemo : Form
{
    private CliClass m_CliObject;
    private System.Threading.CancellationTokenSource m_Cts;
    private System.Threading.CancellationToken m_Ct;

    private void FrmDemo_Load(object sender, EventArgs e)
    {
        // Creating the external CliObject:
        this.m_CliObject = new NSDemo.CliClass();
        ...
    }

    // Event handler of the button starting the cancelable asynchrone operation:
    private async void btnStart_Click(object sender, EventArgs e)
    {
        m_Cts = new System.Threading.CancellationTokenSource();
        m_Ct = m_Cts.Token;
        await Task.Factory.StartNew(() =>
        {
              // Launching a cancelable operation performed by a managed C++Cli Object :
              this.m_CliObject.DoSomething();   // How to eventually pass the CancellationToken m_ct to the m_CliObject ?
        }, m_ct);
        ...
    }


    //Event handler of the cancel button:
    private void btnCancel_Click(object sender, EventArgs e)
    {
        // Requesting cancellation:
        m_Cts.Cancel();
        // (Or alternatively, how to eventually force the termination of the async Task without collaboration from it ?)
    }

CliClass.h:-----------------------------------------------------

#include "DemoCore.h"

using namespace System;
using namespace System::Runtime::InteropServices;
using namespace cli;

namespace NSDemo
{
    public ref class CliClass
    {

    public:

        CliClass();

        ~CliClass(); 

        void DoSomething()
        {
            // Performing the operation in the unmanaged coreObject:
            _coreObject->DoSomething();
        }

    private:
        UNSDemo::CoreClass *_coreObject;
        bool _disposed;

    };
}

CliClass.cpp:------------------------------------------

namespace NSDemo
{
    CliClass::CliClass()
    {
         _coreObject = new UNSDemo::CoreClass(...);
        ....
    }

    CliClass::~CliClass()
    {
        if (_disposed)
            return;               
        if (_coreObject != nullptr) {
            delete _coreObject;
            _coreObject = nullptr;
        }
        _disposed = true;
        GC::SuppressFinalize(this);
    }

CoreClass.h-----------------------------------------------------------------

namespace UNSDemo {

    class __declspec(dllexport) CoreClass {
    public:
        ScanningCore();

        ~ScanningCore();

        void DoSomething();

    private:

    ...

    };

}

CoreClass.cpp:----------------------------------------------------------------------------

#include "CoreClass.h"

namespace UNSDemo {

    CoreClass::CoreClass()
    {
        ...
    }

    CoreClass::~CoreClass()
    {
        ...
    }

    // Method actually performing the cancelable operation:
    void CoreClass::DoSomething()
    {
        // Main loop of the unmanaged cancelable operation:
        while (...) {
            ...
            // How to check the cancellation request from here ? (How to access the CancellationToken ?)
            // and if cancellation is requested, how to eventually throw the OperationCanceledException ?

        }
    }
}

感谢您的帮助。
1个回答

5
如果你正在处理纯非托管代码,它不知道CancellationToken类,所以你不能像处理托管代码那样传递它。
我建议声明你的非托管方法来接受一个指向布尔值的指针,如果该布尔值为真,则中止非托管代码。在你的包装器中,使用CancellationToken.Register注册一个回调函数,当CancellationToken被取消时,该回调函数将把布尔值设置为真。
这听起来很简单,但它有一些复杂之处,因为你需要一个可以访问允许你取地址的布尔值的托管事件处理程序。
public ref class CancelableTaskWrapper
{
private:
    bool* isCanceled;
    void (*unmanagedFunctionPointer)(bool*);

    void Canceled() { if (isCanceled != nullptr) *isCanceled = true; }

public:
    CancelableTaskWrapper(void (*unmanagedFunctionPointer)(bool*))
    {
        this->unmanagedFunctionPointer = unmanagedFunctionPointer;

        isCanceled = new bool;
    }

    ~CancelableTaskWrapper() { if (isCanceled != nullptr) delete isCanceled; isCanceled = nullptr; }
    !CancelableTaskWrapper() { if (isCanceled != nullptr) delete isCanceled; isCanceled = nullptr; }

    void RunTask(CancellationToken cancelToken)
    {
        *isCanceled = false;
        CancellationTokenRegistration reg = cancelToken.Register(
            gcnew Action(this, &CancelableTaskWrapper::Canceled));
        unmanagedFunctionPointer(isCanceled);
    }
};

void someUnmanagedFunction(bool* isCanceled)
{
    doSomethingLongRunning();
    if(*isCanceled) return;
    doSomethingLongRunning();
}
  • 因为isCanceled是指向bool类型的指针,所以它在堆上。因此,我们可以传递一个指向它的指针,而不需要做任何特殊处理(例如固定托管对象)。
  • CancellationTokenRegistration实现了IDisposable接口,当reg超出范围时,它将自动注销自己。(在C#中,您可以使用using语句实现这一点。)

免责声明:我现在不在编译器旁边;可能会有语法错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接