title: Casting Error When using tasks in C# Windows Forms Webrowser
body: <p>I keep getting a casting error when calling a method that then calls a thread that sleeps for a period of time then returns and continues on the original thread. I use the await command to pause the main thread until the sleep thread returns. I can't figure it out but if I avoid the threading then the casting error vanishes.? Very weird to me but i'm new to multithreading. The error occurs in the login method where I check this (webBrowser1.Document != null &amp;&amp; webBrowser1.Document.GetElementById("login_password") != null)    Even if I remove this if statement the very next statement regardless of what it is throws the same error.</p>
  
  <pre><code> private async void main() {
          Console.WriteLine("Main");
          Task generatePassTask = new Task(generatePass);
          Task loginControllerTask = new Task(loginController);
          Task balanceControllerTask = new Task(balanceController);
          //Starts delay and waits for completion.
          generatePassTask.Start();
          await generatePassTask;
  
          loginControllerTask.Start();
          await loginControllerTask;
  
          balanceControllerTask.Start();
          await balanceControllerTask;
  
  
      }
  
      private async void loginController() {
          Console.WriteLine("loginController");
          Task resetDelayTask = new Task(resetDelay);
  
          //Starts delay and waits for completion.
          resetDelayTask.Start();
          await resetDelayTask;
  
          Task loginTask = new Task(login);
  
          //Starts delay and waits for completion.
          loginTask.Start();
          await loginTask;
  
  
          //Calls login method once delay has completed.
          //login();
      }
      private void login() {
          Console.WriteLine("login");
          if (webBrowser1.Document != null &amp;&amp; webBrowser1.Document.GetElementById("login_password") != null)
          {
              webBrowser1.Document.GetElementById("login_password").SetAttribute("value", pass);
              HtmlElementCollection elems = webBrowser1.Document.GetElementsByTagName("Button");
              foreach (HtmlElement elem in elems)
              {
                  string htmlStr = elem.InnerHtml;
                  if (htmlStr != null &amp;&amp; htmlStr.Length != 0 &amp;&amp; htmlStr.Equals("&lt;i class=\"fa fa-arrow-right text-muted\"&gt;&lt;/i&gt;"))
                  {
                      elem.InvokeMember("Click");
                  }
              }
          }
          else {
              loginController();
          }
      }
  
      //Called after logout to sync worker and ui before next login. 
      private static void resetDelay()
      {
          Console.WriteLine("resetDelay");
          Thread.Sleep(1400);
      }
  </code></pre>
  
  <p>Any help would be awesome!!! I've been stuck on this for hours. </p>