1

Объясните пожалуйста почему не работает. На форме в Load_Form такой код:

    Timer timer = new Timer();

    public Form1()
    {
        InitializeComponent();
    }

    private async void Form1_Load(object sender, EventArgs e)
    {
        await Task.Run(() =>
        {
            SetTimer();
        });
    }

    public void SetTimer()
    {
        timer = new Timer();
        timer.Interval = 1000;
        timer.Tick += new EventHandler(timer_Tick);
        timer.Enabled = true;
    }

    void timer_Tick(object sender, EventArgs e)
    {
        label1.Text += 1;
    }

Метод timer_Tick не срабатывает, почему?

4
  • 1
    а Timer у вас из какого пространства имён?
    – 4per
    13 дек 2017 в 12:58
  • @4per System.Windows.Forms; 13 дек 2017 в 13:02
  • уберите 'await Task.Run(() =>'. 13 дек 2017 в 13:24
  • Вот тут есть про поведение различных таймеров: ru.stackoverflow.com/a/696486/10105
    – VladD
    13 дек 2017 в 15:11

1 ответ 1

4

System.Windows.Forms.Timer не поддерживает использование из нескольких потоков. Об этом явно написано в документации:

... This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread.

В зависимости от ситуации можете попробовать:

  • Использовать другие таймеры, например System.Timers.Timer или System.Threading.Timer.
  • Создавать и запускать таймер из потока пользовательского интерфейса.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.