Coffeehouse Thread

20 posts

Question on C# Threads

Back to Forum: Coffeehouse
  • User profile image
    evildictait​or

    It's not clear that osThread is definitely assigned in all of the code blocks in ddRelTypeSelected. If any block doesn't assign it, osThread will still be null when you touch fetchReleases.

    Additionally, it's a real shame that you can't use Future<T> (it's .NET), but here's a slightly less capable one that you might want to try out (warning: I haven't actually tested it)

    class Future<T>
    {
      volatile T value;
      volatile Exception e;
      BackgroundWorker bgw;
      AutoResetEvent done = new AutoResetEvent(false);
      public Future(Func<T> generator)
      {
        bgw = new BackgroundWorker();
        bgw.DoWork += (sender,e) => {
          if(e.Cancel) return;
          try {
            value = generator();
          } catch(Exception e) { this.e = e; }
          } finally { 
            doneEvent.Set();
         }
        };
        bgw.DoWorkAsync();
      }
      public T Value {
        get { 
          done.WaitOne(); // wait for the thing to finish
          if(e != null) throw e; // throw the exception synchronously if necessary
          return value; // the value, as set by the background worker
       }
      }
    }

    Use like:

    string[] fetchReleases()
    {
      Future<List<string>> pendingOses = new Future<string>( () => getReleases("OS") );
      Future<List<string>> pendingGames = new Future<string>( () => getReleases("Games") );

      List<string> games = pendingGames.Value;
      List<string> oses = pendingOses.Value;

      List<string> both = new List<string>();
      both.AddRange(games);
      both.AddRange(oses);

      return both.ToArray();
    }

    (note, you'll need to change getReleases to return the List<string>).

  • User profile image
    pavone

     You are correct, it's not assigned unless a set of specific menu items are selected from drop down menus, however I've made sure to make those selections and I know that it's been assigned by using the debugger. The thread runs, fills the list, and then is somehow set to null.

     I'm very new to C# Threading, so I'm learning a lot through this project. Our website was initially done in ASP.NET Framework 2.0, I've changed it to 3.5 but the server does not support anything above that, so now I'm looking through the multiple ways of accomplishing this and best practices. Currently going through "C# in a Nutshell" which has been great. Your suggestions are much appreciated.

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.