【发布时间】:2009-07-16 00:00:17
【问题描述】:
在开始之前,我想指出我很确定这确实发生了。我所有的日志都表明确实如此。
我想知道我是不是错了,这是不可能的,是不是非常不可能(我怀疑),或者是不是不太可能,我做的事情根本上是错误的。强>
我有 4 个相同代码的实例作为 Windows 服务在同一台服务器上运行。此服务器有一个多核 (4) 处理器。
以下是代码摘要:
public class MyProcess
{
private System.Timers.Timer timer;
// execution starts here
public void EntryPoint()
{
timer = new System.Timers.Timer(15000); // 15 seconds
timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
timer.AutoReset = false;
Timer_Elapsed(this, null);
}
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
string uid = GetUID();
// this bit of code sends a message to an external process.
// It uses the uid as an identifier - these shouldn't clash!
CommunicationClass.SendMessage(uid);
timer.Start();
}
// returns an 18 digit number as a string
private string GetUID()
{
string rndString = "";
Random rnd = new Random((int)DateTime.Now.Ticks);
for (int i = 0; i < 18; i++)
{
rndString += rnd.Next(0, 10);
}
return rndString;
}
接收这些消息的外部进程感到困惑 - 我认为是因为相同的 uid 来自两个独立的进程。基于此,GetUID() 方法似乎为两个单独的进程返回了相同的“随机”18 位字符串。
我使用 DateTime.Now.Ticks 为 Random 类播种,我认为这会在线程之间提供保护 - 一个滴答声是 100 纳秒,当然两个线程无法获得相同的种子值。
我显然没有考虑到我们不是在谈论线程,而是在谈论多核处理器上的进程。这意味着这段代码可以字面上同时运行两次。我认为这就是造成冲突的原因。
以大约 15 秒的间隔运行相同代码的两个进程设法在 100 纳秒内命中相同的代码。这可能吗?我在正确的轨道上吗?
非常感谢您的想法或建议。
为了澄清,我不能真正使用 GUID - 我正在与之通信的外部进程需要一个 18 位数字。太旧了,可惜改不了了。
【问题讨论】:
标签: c# .net multithreading random multicore