Self class

I have a class that controls the process. When calling Stop()or Dispose()in this class, it will first send a TCP command to the process to ask it to close itself, and then look back after 1 second, if it is not closed, call CloseMainWindow(), then wait another second, if it is still running, call Kill().

Now I have List<>this class for managing a bunch of processes. When I would like to remove them from the list, I would manually call Dispose(), then Remove(). I want to make sure that I call Dispose()before losing the only link. Since the call Dispose()will take at least 2 seconds to return, it will take some time if I say that 5 items will be deleted.

So, I intended to have another function called SafeDispose()that returns Invoke() Dispose(). Now remove them from the list and call SafeDispose()instead Dispose()will be immediately, while the classes themselves will be utilized slowly.

Is it advisable to do this?

+3
source share
3 answers

Essentially, you suggest leaving Dispose “as is” and instead getting a helper method that will asymmetric the object asynchronously - which is bound to the object.

Is it possible?

Perhaps the tricky thing about introducing threads is all that is associated with this thread.

  • What happens when another method accesses an object when it is deleted asynchronously?
  • What happens when another AsyncDispose is called at the same time?
  • How are errors propagated?
  • ?
  • ( ), - ? (, tcp)

, , .

, , , ( )

+2

class Program
{
    static void Main(string[] args)
    {
        using (MyClass c = new MyClass())
        {
            c.Disposed += MyClass_Disposed;
            Console.WriteLine("Press any key to dispose");
            Console.ReadKey();
        }
        Console.WriteLine("Press any key to finish");
        Console.ReadKey();
    }

    static void MyClass_Disposed(object source, EventArgs e)
    {
        Console.WriteLine("I've been disposed");
    }
}


class MyClass : IDisposable
{
    public event EventHandler Disposed;

    public void Dispose()
    {
        if (this.Disposed != null)
            this.Disposed(this, EventArgs.Empty);
    }
}
0

Use the asynchronous invoke method to remove objects and then remove them from the list.

Say you have a list of the foo class to host the called foos .

var iars = new List<IAsyncResult>();
Action<IDisposable> disposeAction = a => a.Dispose();
foreach(var foo in foos)
    iars.Add(disposeAction.BeginInvoke(null, null));
foreach(var iar in iars)
    disposeAction.EndInvoke(iar);
foreach(var foo in foos) foos.Remove(foo);

If you are using .net 4.0, you can do this using the Parallel library for greater efficiency. Edit - A popular demand for List.Remove thread safety. Regarding security exceptions. The Dispose () method should never throw an exception in the first place.

0
source

Source: https://habr.com/ru/post/1795135/


All Articles