C# 尝试修改字典时发生异常
我正在创建一个字典来管理线程,当我在字典中添加一些线程后试图清除死线程时,遇到了这个异常C# 尝试修改字典时发生异常,c#,.net,exception,dictionary,C#,.net,Exception,Dictionary,我正在创建一个字典来管理线程,当我在字典中添加一些线程后试图清除死线程时,遇到了这个异常 using System; using System.Collections.Generic; using System.Threading; namespace SysCat { public class ThreadManager { public static readonly ThreadManager GlobalThreadManager = new ThreadMan
using System;
using System.Collections.Generic;
using System.Threading;
namespace SysCat {
public class ThreadManager {
public static readonly ThreadManager GlobalThreadManager = new ThreadManager( );
/// <summary>
/// Initializes a new instance of the <see cref="SysCat.ThreadManager"/> class.
/// </summary>
public ThreadManager( ) {
}
/// <summary>
/// Create a new ThreadManager with all the Threads within baseTM and deinitializes baseTM
/// </summary>
public ThreadManager( ThreadManager baseTM ) {
this.threads = baseTM.threads;
baseTM.threads.Clear( );
}
private Dictionary<Guid,Thread> threads = new Dictionary<Guid, Thread>( );
/// <summary>
/// Attempts to obtain an unused ThreadID within an attempt limit
/// </summary>
/// <returns>The unused ThreadID, if found</returns>
/// <param name="attempts">The number of iterations to try.</param>
public Guid getUnusedThreadID( int attempts ) {
lock( threads ) {
Guid threadID;
int totalAttempts = attempts;
while( threads.ContainsKey( ( threadID = Guid.NewGuid( ) ) ) ) {
attempts--;
if( attempts == 0 )
throw new NoOpenThreadIDException( totalAttempts );
}
return threadID;
}
}
/// <summary>
/// Attempts to get a Thread via its ThreadID, if it exists
/// </summary>
/// <returns>The Thread</returns>
/// <param name="threadID">The ThreadID to use</param>
public Thread getThread( Guid threadID ) {
lock( threads ) {
Thread tryGet;
if( !threads.TryGetValue( threadID, out tryGet ) )
throw new ArgumentException( "Specified ThreadID does not exist in this ThreadManager" );
return tryGet;
}
}
/// <summary>
/// Attempts to get a ThreadID via the Thread
/// </summary>
/// <returns>The ThreadID</returns>
/// <param name="thread">The Thread to use</param>
public Guid getThreadID( Thread thread ) {
lock( threads ) {
if( threads.ContainsValue( thread ) ) {
foreach( Guid id in threads.Keys ) {
Thread t;
threads.TryGetValue( id, out t );
if( t.Equals( thread ) )
return id;
}
// I should never get here
return Guid.Empty;
}
else
throw new ArgumentException( "Specified Thread does not exist in this ThreadManager" );
}
}
/// <summary>
/// Adds the Thread, unless it cannot find an open ThreadID
/// </summary>
/// <returns>The ThreadID used to register the Thread</returns>
/// <param name="thread">The Thread to register</param>
public Guid addThread( Thread thread ) {
lock( threads ) {
Guid id;
try {
id = getUnusedThreadID( 500 );
}
catch( NoOpenThreadIDException e ) {
throw e;
}
threads.Add( id, thread );
return id;
}
}
/// <summary>
/// Attempts to clear all stopped and null Threads
/// </summary>
/// <returns>The number of dead Threads cleared</returns>
public int clearDeadThreads() {
int cleared = 0;
lock(threads) {
foreach( Guid id in threads.Keys ) {
Thread thread;
threads.TryGetValue( id, out thread );
if( thread == null ) {
// Does not exist, Thread is dead
cleared++;
threads.Remove( id );
continue;
}
if( !thread.IsAlive ) {
// Not alive, Thread is dead
cleared++;
threads.Remove( id );
continue;
}
}
}
return cleared;
}
public class NoOpenThreadIDException : Exception {
public NoOpenThreadIDException( int attempts )
: base( string.Format( "Unable to find an open ThreadID within the attempt limit of {0}", attempts ) ) {
}
}
}
}
在枚举时,不能修改
IEnumerable
你可以做一个简单的破解,获得你正在枚举的内容的副本,这样更改就不会导致System.InvalidOperationException
例如,而不是
foreach( Guid id in threads.Keys)
使用
请记住,您可以使用我正在使用lock来同步代码。不过,感谢您向我指出并发部分。在我的方法列表中,我看不到这一点,它是否仅存在于.net的特定版本中?请尝试使用System.Linq添加
。谢谢您的帮助!让我让accept的倒计时结束。
foreach( Guid id in threads.Keys)
foreach( Guid id in threads.Keys.ToList())