귀하의 MainPage
생성자가 종료 결코보십시오. 또한 과Task.Delay
을 UI 스레드에서 호출하고 있습니다.이 번호는 아니오입니다. 당신은 배경 스레드에서해야합니다.
가
public sealed partial class MainPage
{
private bool running;
public MainPage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
running = true;
// Start background thread
Task.Run(
async() =>
{
int counter = 0;
while (running)
{
// UI updates must happen on the UI thread;
// we use the Dispatcher for this:
await Dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
() => test.Text = counter.ToString());
await Task.Delay(1000);
++counter;
}
});
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
running = false;
}
대응 XAML : 여기서
더 나은 접근법의 골격의
<Page
x:Class="App2.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<TextBlock
x:Name="test"
FontSize="24"
HorizontalAlignment="Center"
Margin="0,24,0,0" />
<!-- The button doesn't do anything; it's just to show that the UI is live -->
<Button
Content="Hello, world!"
HorizontalAlignment="Center"
Margin="0,24,0,0" />
</StackPanel>
</Page>
루프를 제어하는 bool
사용은, 비록 약간 하찮은이고; 더 나은 접근법은 을 사용하는 것인데, Task.Delay
을 트랙에서 멈출 수 있습니다. 다른 테이크가 있습니다 :
public sealed partial class MainPage
{
private CancellationTokenSource cancellationTokenSource;
public MainPage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
// Start background thread
Task.Run(
async() =>
{
int counter = 0;
while (true)
{
if (token.IsCancellationRequested)
{
// Stop the loop; we're moving away from the page
break;
}
// UI updates must happen on the UI thread;
// we use the Dispatcher for this:
await Dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
() => test.Text = counter.ToString());
await Task.Delay(1000, token);
++counter;
}
});
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
cancellationTokenSource?.Cancel();
}
}
'MainPage' 메소드가 종료되지 않았으므로 어쩌면 그 이상의 이유가 있을까요? 아마도 타이머를 사용하여이 메서드를 다시 엔지니어링하여 호출하도록해야합니다. – DavidG
어떻게 그 일을 할 것입니까? args에서 .net 프레임 워크를 통해 타이머 클래스를 살펴보고자하는데, 탐색기의 위치를 어디에서 찾을 지 모르겠다. – MattyAB