我正在尝试编写一个函数,为每个"联系人"启动一个线程,然后(通过网络)查询该联系人的结果.我希望我的等待函数等待最多1.5秒的响应,然后,只需终止任何剩余的线程.
我遇到的问题是函数在所有线程完成之前返回,即使根据逻辑,这也不可能.main函数中的while循环应该等待所有线程完全完成,但我得到以下输出:
FAIL: Storage test 1 exists 0 times in the DHT.
: Storage test 2 exists 0 times in the DHT.
Added storage test 1 to the entries.
Added storage test 2 to the entries.
Run Code Online (Sandbox Code Playgroud)
(FAIL行来自主要测试程序,看看Get()返回了多少结果.)
据我所知,这是不可能的.有谁知道竞争条件可能发生在哪里(或者我做过的任何其他假设都不正确)?
功能定义如下:
public IList<Entry> Get(ID key)
{
ConcurrentBag<Entry> entries = new ConcurrentBag<Entry>();
List<Thread> threads = new List<Thread>();
foreach (Contact c in this.p_Contacts)
{
Thread t = new Thread(delegate()
{
try
{
FetchMessage fm = new FetchMessage(this, c, key);
fm.Send();
int ticks = 0;
// Wait until we receive data, or timeout.
while (!fm.Received && ticks < 1500)
{
Thread.Sleep(100);
ticks += 100;
}
if (fm.Received)
{
foreach (Entry e in fm.Values)
{
Console.WriteLine("Added " + e.Value + " to the entries.");
entries.Add(e);
}
if (entries.Count == 0)
Console.WriteLine("There were no entries to add.");
}
else
Console.WriteLine("The node did not return in time.");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
);
t.IsBackground = false;
t.Start();
}
while (true)
{
bool stopped = true;
foreach (Thread t in threads)
{
if (t.ThreadState != ThreadState.Stopped)
stopped = false;
}
if (stopped)
break;
Thread.Sleep(100);
}
return new List<Entry>(entries.ToArray());
}
Run Code Online (Sandbox Code Playgroud)