使用托管 C++ CLI 从 C++ 更新 C# 进度条

C# progressbar update from c++ using managed c++ cli

我是 C# 和 C++ 混合编程的新手。

我的 C# 应用程序有一个 ProgressBar。单击按钮时,通过 c++/CLI 包装器 class DLL 调用 c++ 函数。这是一个耗时的功能。因此,我想在我的 c# 应用程序的 ProgressBar 上显示状态更新。

UI不应该被阻塞,因此使用了backgroundworker;在它的 DoWork 中,我调用了 DLL 方法。请提供代码。

[我得到的一个线索是我需要使用委托,但我是 C++/CLI 的新手,因此无法使用。]

代码片段会有很大帮助。

您需要一个更新进度条的托管方法(C# 或 C++/CLI),该方法以百分比作为参数。让托管方法处理任何必要的线程;您可能需要调用 UI 线程。

将其转换为 C++ 函数指针,并将其传递给您的 long-运行 C++ 函数。让 long-运行 C++ 函数定期调用函数指针。

你可以使用 BackgroundWorker here, but I'd skip it, personally. You'd have to do a lot of plumbing to get everything working right, and if all you're interested in is reporting progress, it's easier to do that directly. Instead, I'd take the direct path, and just call your C++ method on a new Thread.

这里有一个没有事件的简单方法

C++:

int progressvalue;

extern "C" __declspec(dllexport) void __cdecl LongRunningMethod(int seconds)
{
    cout << "Started" << endl;

    progressvalue = 0;
    for (size_t i = 0; i < seconds; i++)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        progressvalue = (seconds - ((double)seconds/ (double)i))*10;
        cout << "Progress value in c++: " << progressvalue << endl;
    }
    cout << "Completed" << endl;
}

extern "C" __declspec(dllexport) int __cdecl GetProgressUpdate()
{
    return progressvalue;
}

以下是如何在 C# 中使用它 c#:

private void button_Click(object sender, RoutedEventArgs e)
{
        var task = Task.Factory.tartNew(() => {
                               NativeMethods.LongRunningMethod(10);});

    Task.Factory.StartNew(() =>
    {
        while (!task.IsCompleted)
        {
            Dispatcher.Invoke(() =>
            {
                var val = NativeMethods.GetProgressUpdate();
                ProgressBarMain.Value = val;
                Thread.Sleep(100);
            });
        }
    });
}