在计时器回调中创建的线程意外终止

发布于 2024-10-01 02:24:25 字数 1081 浏览 1 评论 0原文

这就是我想要做的:

  1. 有一个具有一定间隔的计时器
  2. 在计时器回调代码中,如果满足某些条件,则应该运行另一个线程

我已将代码放入一个由主窗体和代码实例化的类中在方法调用时执行(“StartSync()”,参见示例代码)。

问题是代码运行了几秒钟,然后终止。我想我在做一些愚蠢的事情,但我真的不明白那是什么。感谢您对此提供的任何帮助。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace WindowsFormsApplication1
{
    class Syncer
    {
        static bool SYNC_IN_PROGRESS;

        public void StartSync()
        {
            SYNC_IN_PROGRESS = false;
            Timer timer = new Timer(timerCallback, null, 0, 1000);
        }

        public void timerCallback(Object stateInfo)
        {
            Debug.WriteLine("Sync?");

            if (!SYNC_IN_PROGRESS)
            {
                SYNC_IN_PROGRESS = true;

                Thread thSync = new Thread(new ThreadStart(sync));
                thSync.Start();
            }
        }

        void sync()
        {
            Debug.WriteLine("Syncing...");
            SYNC_IN_PROGRESS = false;
        }
    }
}

This is what I want to do:

  1. Have a timer with some interval
  2. In the timer callback code, if some condition is met, another thread should be run

I’ve put my code in a class which is instantiated by the main form and the code is executed upon method call (‘StartSync()’, se sample code).

The problem is that the code runs for a couple of seconds but then terminates. I suppose I’m doing something stupid but I really can’t see what it is. Thankful for any help with regards to this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace WindowsFormsApplication1
{
    class Syncer
    {
        static bool SYNC_IN_PROGRESS;

        public void StartSync()
        {
            SYNC_IN_PROGRESS = false;
            Timer timer = new Timer(timerCallback, null, 0, 1000);
        }

        public void timerCallback(Object stateInfo)
        {
            Debug.WriteLine("Sync?");

            if (!SYNC_IN_PROGRESS)
            {
                SYNC_IN_PROGRESS = true;

                Thread thSync = new Thread(new ThreadStart(sync));
                thSync.Start();
            }
        }

        void sync()
        {
            Debug.WriteLine("Syncing...");
            SYNC_IN_PROGRESS = false;
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

千鲤 2024-10-08 02:24:25

猜测Timer仅保存在方法变量中; 对我来说听起来就像Timer正在收集垃圾并最终确定,因此终止。我怀疑您应该在字段中保留该引用以防止收集。

顺便说一句 - 我怀疑这是这里的原因,但是在处理线程时,您应该认真地意识到从多个线程访问共享状态;例如:

  • 使用Monitor(又名lock
  • 情况下适当使用易失性
  • 在适合

您当前访问的 Interlocked static bool可能可以正常工作,但是......

At a guess, the Timer is only held in a method variable; it sounds to me like the Timer is getting garbage collected and finalized, hence terminated. I suspect you should hold onto that reference in a field to prevent collection.

As an aside - I doubt it is the cause here, but when dealing with threading you should be religiously aware of access to shared state from multiple threads; for example:

  • using Monitor (aka lock)
  • appropriate use of volatile
  • Interlocked when it fits

Your current access to the static bool will probably work OK, but...

始于初秋 2024-10-08 02:24:25

尝试这种更干净的方法

    static volatile bool SYNC_IN_PROGRESS; 
    static thread syncPoll; 

    public void StartSync() 
    { 
        SYNC_IN_PROGRESS = false; 
        syncPoll = new Thread(sync);
        syncPoll.Start();
    } 

    void sync() 
    { 
        while (true)
        {
             Debug.WriteLine("Sync?");
             if (SYNC_IN_PROGRESS) Debug.WriteLine("Syncing..."); 
             Thread.Sleep(1000);
        }
    } 

它的作用与您尝试对当前代码执行的操作相同:)但不使用计时器

Try this cleaner approach

    static volatile bool SYNC_IN_PROGRESS; 
    static thread syncPoll; 

    public void StartSync() 
    { 
        SYNC_IN_PROGRESS = false; 
        syncPoll = new Thread(sync);
        syncPoll.Start();
    } 

    void sync() 
    { 
        while (true)
        {
             Debug.WriteLine("Sync?");
             if (SYNC_IN_PROGRESS) Debug.WriteLine("Syncing..."); 
             Thread.Sleep(1000);
        }
    } 

It does the same you try to do with your current code :) but doesn't use a timer

一个人的旅程 2024-10-08 02:24:25

这就是我所做的,看起来效果很好

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            StartSync();
        }

        static bool SYNC_IN_PROGRESS;

        public void StartSync()
        {
            SYNC_IN_PROGRESS = false;
            System.Threading.Timer timer = new System.Threading.Timer(timerCallback, SYNC_IN_PROGRESS, 0, 1000); 


        }

        public void timerCallback(Object stateInfo)
        {
            Debug.WriteLine("Sync?");

            if (!(bool)stateInfo)
            {
                SYNC_IN_PROGRESS = true;

                Thread thSync = new Thread(new ThreadStart(sync));
                thSync.Start();
            }
        }

        void sync()
        {
            Debug.WriteLine("Syncing...");
            SYNC_IN_PROGRESS = false;
        }
    }

So here is what I did and it seems to work just fine

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            StartSync();
        }

        static bool SYNC_IN_PROGRESS;

        public void StartSync()
        {
            SYNC_IN_PROGRESS = false;
            System.Threading.Timer timer = new System.Threading.Timer(timerCallback, SYNC_IN_PROGRESS, 0, 1000); 


        }

        public void timerCallback(Object stateInfo)
        {
            Debug.WriteLine("Sync?");

            if (!(bool)stateInfo)
            {
                SYNC_IN_PROGRESS = true;

                Thread thSync = new Thread(new ThreadStart(sync));
                thSync.Start();
            }
        }

        void sync()
        {
            Debug.WriteLine("Syncing...");
            SYNC_IN_PROGRESS = false;
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文