Calling method indefinitely

2019-12-16 19:21发布

问题:

I want to use a .dll created with c++/cli that includes normal c code in an c# wpf project. A function of the c code needs permanent calling. This function was orginally called in an endless loop in the main function of a c command-line-application.

How do I call a function permanently from a wpf c# project without interfering with the rest of the application? I guess that should be pretty easy but Im new to wpf and fairly new to .Net.

回答1:

using System.Threading;

Thread t = new Thread(()=>{
while(true)
{
//call your method here...
Thread.Sleep(500); //optional if you want a pause between calls.
}
});
t.IsBackground = true;
t.Start();


回答2:

You can have a while(true) loop on another thread.



回答3:

If I understood correctly, all you want to do is keep calling the method? Use a timer:

Include using System.Windows.Threading; at the top of the file. Then write:

DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(x); //x is the amount of milliseconds you want between each method call

timer.Tick += (source, e) =>
{
    method();
};
timer.Start();

The timer will run your method with every tick, and you can write additional code in the anonymous method to control how often/how many times your method is called, when it is called, and so on. And of course, it won't interfere with the rest of your program.

If you want to call your program as often as possible, replace x in the second line with 1.



标签: c# wpf c++-cli