我知道你有一種方法可以從一個偶數部分,從一個完整的id中找出一個奇數部分,並且你有一種方法可以告訴你的消息的來源。在這種情況下,我會在字典中存儲奇數部分(如果它們總是先接收到的)。當我收到偶數部分時,我會檢查是否存在相應的奇數部分,如果是這種情況,我會處理整個事情,否則我會丟棄它。此外,當我收到一個奇怪的部分時,我會啓動一個計時器,負責在10秒鐘後將其從字典中刪除。由於定時器必須停止,它也會存儲在字典中。就像這樣(這只是一個例子,可能你想創建一些實例變量以避免在任何地方傳遞參數):
Dictionary<string, string> oddParts = new Dictionary>string, string>();
Dictionary<string, Timer> timers = new Dictionary<string, Timer>();
while (serialportopen)
{
// somedecoding I end up with
string hexid;
string oddpart;
string evenpart;
// you need something to identify where the message came from and that is present in both the odd and even part (the BF... of your previous question)
string msgId;
if (!String.IsNullOrEmpty(oddpart))
ProcessOddPart(msgId, oddpart, oddParts, timers);
else if (!String.IsNullOrEmpty(evenpart))
hexid = HexIdFromEvenPart(msgId, evenpart, oddparts, timers);
if (!String.IsNullOrEmpty(hexid))
Process(hexid);
}
void Process(string hexid)
{
// your stuff here
}
void ProcessOddPart(string msgId, string oddPart, Dictionary<string, string> oddParts, Dictionary<string, Timer> timers)
{
oddParts[msgId] = oddPart;
System.Timers.Timer tmr = new Timer();
timers[msgId = tmr;
ElapsedEventHandler timePassed = delegate(object anObj, ElapsedEventArgs args) {
tmr.Stop();
oddParts.Remove(msgId);
timers.Remove(msgId);
};
tmr.Interval = 10000;
tmr.Elapsed += timePassed;
tmr.Start();
}
void HexIdFromEvenPart(string msgId, string evenPart, Dictionary<string, string> oddParts, Dictionary<string, Timer> timers)
{
string oddPart;
Timer tmr;
if (timers.TryGetValue(msgId, out tmr))
{
tmr.Stop();
timers.Remove(msgId);
}
if (!oddParts.TryGetValue(msgId, out oddPart))
return null;
return oddPart + evenPart;
}
請不要在「C#」前加標題。這就是我們在SO上的標籤。 –
請說出爲什麼這不是您早期問題的重複,請訪問http://stackoverflow.com/questions/6976156/giving-a-class-instance-the-name-of-a-variable。 –
,因爲它的另一個問題 –