在Windows Embedded Application中获取毫秒分辨率(循环时间)

时间:2015-09-09 14:25:16

标签: c# windows timer

我在C#中创建一个应用程序,它读取CAN(控制区域网络)消息并发送它们。我需要在10毫秒内完成。我使用的操作系统是Windows Embedded 7 Pro。

    public void ID0008Update10ms(DataTable supportPoints, int a)
    { 
        System.TimeSpan timer10ms = System.TimeSpan.FromMilliseconds(10); 
        intialiseCAN();
        while (a==1)
        {
            Stopwatch t = Stopwatch.StartNew();
            sendCAN();
            getCAN();
            ID0006NavComStatus(supportPoints);
            string state = Convert.ToString(gNavStatus);


            while (t.Elapsed < timer10ms) 
            { /*nothing*/}
        }

    }

问题是sendCAN()和reciveCAN()动态加载.dll文件

    public int sendCAN(ref can_msg msg, IntPtr pDll)
    {
        if (pDll == IntPtr.Zero)
        {
            MessageBox.Show("Loading Failed");
        }
        IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "CAN_Transmission");
        CAN_Transmission sendCAN = (CAN_Transmission)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(CAN_Transmission));

        int result = sendCAN( ref msg);
        return result;
    }

这使循环变慢,我无法在10ms内发送消息。任何人都可以提出更好的方法。请记住。我使用的是Windows Embedded。

1 个答案:

答案 0 :(得分:1)

你应该尽可能多地在循环之外移动。如果它不是绝对必须在那里,移动它。沿着......的路线。

private CAN_TransmissionMethod CAN_Transmission;

//Cache the delegate outside the loop.
private bool InitialiseCAN2(IntPtr pDll)
{
    if (pDll == IntPtr.Zero)
    {
        Log("Loading Failed");
        return false;
    }
    IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "CAN_Transmission");
    CAN_Transmission = (CAN_TransmissionMethod)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(CAN_Transmission));
    return true;     
}

public int sendCAN(ref can_msg msg)
{
    if (CAN_Transmission == null)
        return -1;//Can't send, no delegate, Log, Fail, Explode... make a cup of tea.
    int result = CAN_Transmission( ref msg);
    return result;
}

public void ID0008Update10ms(DataTable supportPoints, int a)
{ 
    System.TimeSpan timer10ms = System.TimeSpan.FromMilliseconds(10); 
    intialiseCAN();
    initialiseCAN2(pDll)
    while (a==1)
    {
        Stopwatch t = Stopwatch.StartNew();
        sendCAN(ref thereIsSupposedToBeAMessageHere);
        getCAN(ref probablySupposedToBeSomethingHereToo);
        ID0006NavComStatus(supportPoints);
        string state = Convert.ToString(gNavStatus);


        while (t.Elapsed < timer10ms) 
        { /*nothing*/}
    }

}