简体   繁体   中英

How Can I Limit CPU core to specific thread in C#

In my program, UDP data is sent and received regularly. If only this one program runs on the entire computer, the result is normal. However, if other operations are performed at the same time (such as opening a PDF document), UDP communication will be affected, and the reception timeout will occur. By observing the task manager, when performing other operations, the CPU usage will increase temporarily, which will affect the running of my program. Since my computer is multi-core (12 cores), I tried to bind my key thread to a certain core, but it still doesn't work, other threads will still be assigned to this core by the system.

keyThread.IdealProcessor = 9;
keyThread.ProcessorAffinity = (IntPtr)512;

I think what I need is to bind a certain CPU core to the key thread of the program, not the other way around. But I did not find a way to do this.

Add some details about my program.

timer.interval = 10;    //10ms
localSocket.Connect(remotePoint);
localSocket.ReceiveTimeout = 10;    //10ms
private void Timer_Ticked() 
{     
    byte[] requestFrame = new byte[1024];     
    requestFrame = frameManager.GenerateFrame();     
    localSocket.Send(requestFrame);     
    try     
    {         
        byte[] responseFrame = new byte[1024];         
        localSocket.Receive(responseFrame);     
    }     
    catch (Exception)     
    {         
        Console.WriteLine("receive timeout");     
    } 
}

I add new code to set the priority of the process to Realtime, and set the priority of the thread to Highest, but still didn't work, when I perform other operation in the computer(like open a PDF file or open the Chrome), my program is affected.

I observe the task manager of Windows 10, when I perform an operation (such as opening a PDF document), there will be a peak in the usage of all CPU cores. Can I specify a CPU core to work only for my program and not be used by other programs?

Rule of thumb: UDP data is the one that CAN be lost, and the system MUST be designed a way to overcome that losses. Otherwise, another protocol to be employed, like TCP with built-in acknowledgements & retries, or SCTP, etc.

Given that, pursuing a goal of UDP stability is a false target. Despite your efforts, sooner or later the system will meet a situation where particular UDP packet is lost. Maybe not by sender nor receiver fault (sic.). That may happen on an interim router somewhere in-between because everyone agrees UDP can be dropped eventually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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