C# 如果操作正在处理IAsyncResult,如何暂停时间

C# 如果操作正在处理IAsyncResult,如何暂停时间,c#,C#,如果动作中有活动,如何暂停 这是我的密码 private void RunWithTimeout(Action action, int timeoutMilliseconds) { Thread threadToKill = null; Action wrappedAction = () => { threadToKill = Thread.CurrentThread; acti

如果动作中有活动,如何暂停

这是我的密码

    private void RunWithTimeout(Action action, int timeoutMilliseconds)
    {
        Thread threadToKill = null;
        Action wrappedAction = () =>
        {
            threadToKill = Thread.CurrentThread;
            action();
        };

        IAsyncResult result = wrappedAction.BeginInvoke(null, null);

        if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds, true))
        {
            wrappedAction.EndInvoke(result);
        }
        else
        {
            threadToKill.Abort();
            wrappedAction = null;
            throw new TimeoutException();
    }

    private void DoSubscription()
    {
        // Subscribe the connection. 
        StompConnection connection = PrepareConnection();
        while (connection.getStompSocket() != null)
        {
            try
            {
                RunWithTimeout(() => StartProcessing(connection), 1200000);// 20 minutes
            }
            catch (Exception e)
            {
                if (e is System.TimeoutException)
                {
                    _log.Debug(GetType().Name + " Timed out. Reconnecting...");
                }
                else
                {
                    SetSubscriptionError(e);
                }
                // Reconnection happens here
                run();
            }
        }
    }

    private void StartProcessing(StompConnection connection)
    {
        // "9999999999" is the timeout before it receive something from STOMP. There is an error in this method (after 5 seconds, it will not throw error, and the server that I subscribed kick me after 20 minutes, so I have to use another method to override this timeout to resubscribe to the server)
        Message = connection.receive(9999999999);
        if (Message.getBody() != null)
        {
            //result = true;
            string msgBody = Message.getBody();

            // Process the message body to extrace data that I need
            OnReceive(msgBody);
        }
        connection.ack(Message, Transaction);
    }
DoSubscription()
是使用
RunWithTimeOut()
的方法。但是,假设超时时间为20分钟,19分58秒时有消息传入,
StartProcessing()
方法未完成执行,一旦达到20分钟,
RunWithTimeOut()
将抛出timeoutexception以结束线程。这意味着我的
StartProcessing()
操作尚未完成

那么,有没有改进我在
StartProcessing()
中有动作时暂停的方法的想法


  • 实际上,它在
    StartProcessing()
    中做了一些事情,它位于
    Message=connection.receive(9999999999)嗯…没人知道解决方案?