ThreadStatic and IDisposable problem RRS feed

  • Question

  • I have the following member:

            private static FileStream _fileStream; 
    This means that each thread will have its own FileStream object.

    The problem is that exiting a thread does NOT disposing the FileStream.

    I need something like catch a "Thread Exit Event" and there dispose the FileStream object.

    Is that possible?

    Wednesday, December 10, 2008 9:16 PM


All replies

  • Why are you making the thread static? Get rid of it and the filestream will be collected by GC in due time. Close it, better with using block.
    Wednesday, December 10, 2008 11:11 PM
  • Presumably, you're creating the FileStream object somewhere near the beginning of your thread procedure. I think the easiest way to handle this is to make it a local using:

      // Other setup code  
      using (FileStream fileStream_guard = ...)  
        fileStream = fileStream_guard;  
        // Main thread procedure/loop that doesn't exit until the thread is ready to exit  

    In this way, the FileStream object's lifetime is scoped to the code that needs it, and the static variable is more of just a convenience, so you don't have to pass it around to various methods.

    Thursday, December 11, 2008 4:02 AM
  • hey

    thanks for answers.

    FileStream is just an example. it could be a connection or something else IDisposable object.

    The point is - i do NOT controlling the thread start and stop.

    assume its a Socket or TcpClient that connected to a server.
    I want that each thread will have its own connection object to prevent thread safety problems.
    I can't controll the thread start and stop (ThreadPool), so i can't just open and close connections.
    i openning a connection like in a singleton: if null --> open new connection (per thread).
    i want to catch the thread exit event to close associated connection object.
    Thursday, December 11, 2008 7:59 PM
  •  Implement an Asynchronous CallBack delegate that will report to you as soon as the thread is finished, or rather the task it is running is done.
    Thursday, December 11, 2008 8:32 PM
  • Can you attach an async callback from a library creating a ThreadStatic instance, if it doesn't control the thread creation?

    It would be nice if IDisposable objects marked ThreadStatic could be disposed immediately when the thread is done, or if some new explicit ThreadStaticDisposeOnExit attribute could do this.

    Wednesday, August 4, 2010 7:39 PM