1

我正在尝试管理线程机器人情况。我想将它们添加到字典中以供以后访问(关闭、暂停、传递变量),但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);
}
4

1 回答 1

1

新线程不知道 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();
于 2013-02-21T09:23:57.880 回答