F
F
Fareed2020-02-21 01:49:41
C++ / C#
Fareed, 2020-02-21 01:49:41

How to write a stopwatch in UWP in C#?

I want to write a stopwatch in UWP in C#. In the constructor, I added a button and a text box named label1. Wrote this code:

using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System.Threading.Tasks;
using System.Timers;
using System.Diagnostics;

namespace Stopwatcher
{
    public sealed partial class MainPage : Page
    {
      
        public MainPage()
        {
            this.InitializeComponent();
        }

        private static System.Timers.Timer aTimer;

        public void MyMain()
        {
            SetTimer();
        }

        private void SetTimer()
        {
            aTimer = new System.Timers.Timer(100);
             
            aTimer.Elapsed += OnTimedEvent;
            aTimer.AutoReset = true;
            aTimer.Enabled = true;
        }

        private void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            label1.Text = "test";
            Debug.WriteLine(e.SignalTime);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MyMain();
            label1.Text = "wdfsff";
            Debug.WriteLine("CYKA");
        }
    }
}


But when the button is clicked, the following error occurs: System.Exception: "The application accessed an interface related to another thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))"

5e4f0d7162319048170883.png

I can't find a solution on the Internet. Help me please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
freeExec, 2020-02-21
@freeExec

Because you can not access the UI from any thread.
https://docs.microsoft.com/en-us/uwp/api/windows.u...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question