简体   繁体   English

在 c++ dll 中启动一个线程,从一个 C# wpf 开始一个线程,内部需要一个线程

[英]Starting a thread in a c++ dll, from a C# wpf application, do I need a thread inside a thread?

I have a C# / WPF application that runs functions from a c++ dll, and returns data into a callback.我有一个 C# / WPF 应用程序,它运行来自 c++ Z06416233FE5EC4C591Z,AF4AB24 的函数并返回数据。

To avoid locking the UI, I start a thread in C# that starts a new thread in the dll.为了避免锁定 UI,我在 C# 中启动了一个线程,该线程在 dll 中启动了一个新线程。

c# c#

Thread threadZ = new Thread(StartTracking);
threadZ.IsBackground = true;
threadZ.Start();

c++ c++

__declspec(dllexport) void StartTracking()
{

    std::thread procThread = std::thread([&]() {
        m.ttrack->Connect(callback, callbackFrames); });

    procThread.join();

}

This seems redundant, as I am starting a thread just to start a thread.这似乎是多余的,因为我启动一个线程只是为了启动一个线程。 But if i do not start a new c# thread, the UI locks up.但是如果我不启动一个新的 c# 线程,UI 就会锁定。 If I just run the function in c++, without starting a new c++ thread, I see strange issues with my returned data, where the latency will rise and fall.如果我只是在 c++ 中运行 function,而不启动新的 c++ 线程,我会看到返回的数据出现奇怪的问题,延迟会上升和下降。 In a new thread, it is stable.在新线程中,它是稳定的。 For example, the latency of my callback data is 6ms when I launch the application.例如,当我启动应用程序时,我的回调数据的延迟是 6 毫秒。 When the application is minimised for a period of time, or I am using another application while it is running, the latency will rise to 800ms or more.当应用程序最小化一段时间,或者我在运行时使用另一个应用程序时,延迟会上升到 800ms 或更多。

My question is:我的问题是:

Do I need to run a thread-inside-a-thread like this?我需要像这样运行线程内线程吗? Or is there a simpler way?或者有没有更简单的方法?

About the use of threads in both C # and C ++.关于 C # 和 C ++ 中的螺纹使用。 Keep in mind that they will be different contexts, so if the following questions have affirmative answers, continue to use them.请记住,它们将是不同的上下文,因此如果以下问题有肯定的答案,请继续使用它们。

1 - In your WPF form, do you want to allow your user to perform other actions while the routine is not completed (responsiveness)? 1 - 在您的 WPF 表单中,您是否希望您的用户在例程未完成时执行其他操作(响应性)?

2 - In the routine created in C ++, consumed by C # through the DLL, are there other activities that can be performed in parallel to the main flow? 2 - 在 C ++ 中创建的例程中,由 C # 通过 DLL 消耗,是否还有其他活动可以与主流并行执行?

As for the latency issue, I would advise you to change your approach a bit.至于延迟问题,我建议您稍微改变一下方法。 Instead of instantiating new threads whenever you use your C ++ routine (new Thread(StartTracking)).而不是在您使用 C ++ 例程(新线程(StartTracking))时实例化新线程。 Try to use the pool of threads managed by.Net .尝试使用由 .Net 管理的线程池 In the past, I have seen significant performance improvements in adopting this approach.过去,我已经看到采用这种方法的性能显着提高。

ThreadPool.QueueUserWorkItem((x)=> StartTracking);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM