Pregunta

I am trying to manage a thread bot situation. I want to add them in a dictionary for later access (shutdown, pause, pass variables) but I always get them as null even after the bot started (the null variable is 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);
}
¿Fue útil?

Solución

The new thread doesn't know about the temp_bot object as you need to pass it in to the lambda expression. Try:

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();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top