字典线程lambda添加
本文关键字:添加 lambda 线程 字典 | 更新日期: 2023-09-27 18:00:19
我正在尝试管理线程机器人的情况。我想把它们添加到字典中,以便以后访问(关闭、暂停、传递变量),但即使在bot启动后,我也总是把它们作为null
(null
变量是temp_bot
)。
private static
Dictionary<string, Bot> BotsOnline = new Dictionary<string, Bot>();
Bot temp_bot;
new Thread(
() =>
{
int crashes = 0;
while (crashes < 1000)
{
try
{
temp_bot = new Bot(config, sMessage, ConvertStrDic(offeredItems),
ConvertStrDic(requestedItems), config.ApiKey,
(Bot bot, SteamID sid) =>
{
return (SteamBot.UserHandler)System.Activator.CreateInstance(
Type.GetType(bot.BotControlClass), new object[] { bot, sid });
},
false);
}
catch (Exception e)
{
Console.WriteLine("Error With Bot: " + e);
crashes++;
}
}
}).Start();
//wait for bot to login
while (temp_bot == null || !temp_bot.IsLoggedIn)
{
Thread.Sleep(1000);
}
//add bot to dictionary
if (temp_bot.IsLoggedIn)
{
BOTSdictionary.Add(username, temp_bot);
}
新线程不知道temp_bot对象,因为您需要将其传递给lambda表达式。尝试:
new Thread(
(temp_bot) =>
{
int crashes = 0;
while (crashes < 1000)
{
try
{
temp_bot = new Bot(config, sMessage, ConvertStrDic(offeredItems),
ConvertStrDic(requestedItems), config.ApiKey,
(Bot bot, SteamID sid) =>
{
return (SteamBot.UserHandler)System.Activator.CreateInstance(
Type.GetType(bot.BotControlClass), new object[] { bot, sid });
},
false);
}
catch (Exception e)
{
Console.WriteLine("Error With Bot: " + e);
crashes++;
}
}
}
).Start();