How to write an intermittent synchronous method?

I need to start the list of methods synchronously, with the ability to stop the execution list. It's easy to stop the loop before executing with the reset event (see first line in Execute).

How can I wait for an answer from action.Execute()and action.Execute()at the same time?

private ManualResetEvent _abortingToken = new ManualResetEvent(false);
private List<IAction> _actions;

public void Abort()
{
    _abortingToken.Set();
}

public void Execute()
{
    foreach (var action in _actions)
    {
        if (_abortingToken.WaitOne(0))
            break; // Execution aborted.

        action.Execute(); // Somehow, I need to call this without blocking

        while (/*Execute not finished*/)
        {
            if (_abortingToken.WaitOne(1))
                action.Abort();
        }
    }
}

I think it would be easy to preform using Tasks, but unfortunately I am using .net 3.5.


Edit: Solution based on SLaks Responses :

public void Execute()
{
    Action execute = null;
    IAsyncResult result = null;

    foreach (var action in _actions)
    {
        execute = new Action(scriptCommand.Execute);

        if (_abortingToken.WaitOne(0))
            break; // Execution aborted.

        result = execute.BeginInvoke(null, null);

        while (!result.IsCompleted)
        {
            if (_abortingToken.WaitOne(10))
            {
                action.Abort();
                break;
            }
        }

        execute.EndInvoke(result);
    }
}
+3
source share
2 answers

This is the opposite of synchronization.
You need to run the method in the background thread.

, Delegate.BeginInvoke, IAsyncResult.IsCompleted. ( EndInvoke )

+2

Execute , -.

public void Execute()
{
    foreach (var action in _actions)
    {
        if (_abortingToken.WaitOne(0))
            break; // Execution aborted.

        var workThread = new Thread(action.Execute); 
        workThread.Start();

        while (!workThread.Join(100)) /Milliseconds, there is also a timespan overload
        {
            if (_abortingToken.WaitOne(1))
                action.Abort();
        }
    }
}

. http://msdn.microsoft.com/en-us/library/system.threading.thread_methods.aspx.

0

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


All Articles