C#C
C#4y ago
.logik.

Application called an interface that was marshalled for a different thread?

Prefacing that I'm very new to C#: I'm trying to implement a very basic timer but I'm getting an wrong thread error in the event function of System.Timers.Timer. An image of the error is attached and the code that I'm working with is below

C#
using System.Timers;

namespace Pomodoro.Views;

public partial class MainPage : ContentPage
{
    int timeLeft = 60;
    private System.Timers.Timer pTimer;


    public MainPage()
    {
        InitializeComponent();

        pTimer = new(1000)
        {
            Enabled = true,
        };

        pTimer.Elapsed += timerTick;
    }

    private void timerTick(object sender, EventArgs e)
    {
        if (timeLeft > 0)
        {
            timeLeft--;
            TimerDisplay.Text=timeLeft.ToString();
        }
        else
        {
            pTimer.Stop();
        }
    } 
    

    private void OnStartTimerClicked(object sender, EventArgs e)
    {
        pTimer.Start();
    }

    private void OnStopTimerClicked(object sender, EventArgs e)
    {
        pTimer.Stop();
    }
}


For reference TimerDisplay is referring to the label in the xaml
<Label
                x:Name="TimerDisplay"
                Text="60"
                SemanticProperties.Description="Display of time remaining"
                FontSize="50"
                HorizontalOptions="Center" />


I feel like I might be doing something wrong from a theoretical point of view with how the eventhandler is defined.
image.png
Was this page helpful?