728x90
반응형
WPF & C# - 시간 딜레이 주기 4가지 방법 ( Time Delay / async await Task / Thread.Sleep ) |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
///// timeDelay01 - All Stop 멈춤
private void btn01_Click(object sender, RoutedEventArgs e)
{
lbl01.Content = DateTime.Now.ToString("G") + " StartTime \r\n";
Thread.Sleep(3000); // 1000은 1초
lbl01.Content += DateTime.Now.ToString("G") + " EndTime \r\n";
}
///// timeDelay02 - 창은 멈추지 않으나 마우스로 창 이동중에는 시간이 흐르지 않음
void timeDelay02(int tDelaySecond)
{
DateTime dtStart = DateTime.Now;
TimeSpan firstTime = new TimeSpan(DateTime.Now.Ticks);
while (firstTime.Ticks + (tDelaySecond * 10000000) >= DateTime.Now.Ticks)
{
TimeSpan elapsedSpan = new TimeSpan(DateTime.Now.Ticks - firstTime.Ticks);
lbl02.Content =
dtStart + " StartTime \r\n"
+ dtStart.AddSeconds(tDelaySecond) + " EndTime \r\n"
+ elapsedSpan.Seconds.ToString();
this.Dispatcher.Invoke((ThreadStart)(() => { }), DispatcherPriority.Input);
}
}
private void btn02_Click(object sender, RoutedEventArgs e)
{
timeDelay02(3); // Second
MessageBox.Show("The End");
}
///// timeDelay03 - 백그라운드에서 시간을 재는 가장 단순하고 좋은 방법
async private void timeDelay03(int tDelaySecond)
{
await Task.Delay(tDelaySecond);
lbl03.Content += DateTime.Now.ToString("G") + " EndTime \r\n";
MessageBox.Show("Completed");
}
private void btn03_Click(object sender, RoutedEventArgs e)
{
lbl03.Content = DateTime.Now.ToString("G") + " StartTime \r\n";
timeDelay03(1000 * 3); // 1000 = 1 Second
MessageBox.Show("The End");
}
///// timeDelay04 - 백그라운드에서 시간을 재는 또다른 방법
private void btn04_Click(object sender, RoutedEventArgs e)
{
lbl04.Content = DateTime.Now.ToString("G") + " StartTime \r\n";
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(3);
timer.Tick += (s, a) =>
{
lbl04.Content += DateTime.Now.ToString("G") + " EndTime \r\n";
MessageBox.Show("Completed");
timer.Stop();
};
timer.Start();
MessageBox.Show("The End");
}
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<Grid>
<StackPanel>
<StackPanel Orientation="Horizontal">
<Button x:Name="btn01" Height="50" Click="btn01_Click">timeDelay01</Button>
<Label x:Name="lbl01"></Label>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Button x:Name="btn02" Height="50" Click="btn02_Click">timeDelay02</Button>
<Label x:Name="lbl02"></Label>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Button x:Name="btn03" Height="50" Click="btn03_Click">timeDelay03</Button>
<Label x:Name="lbl03"></Label>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Button x:Name="btn04" Height="50" Click="btn04_Click">timeDelay04</Button>
<Label x:Name="lbl04"></Label>
</StackPanel>
</StackPanel>
</Grid>
|
cs |
[ 참고 ]
https://blog.naver.com/computer_king/222031639599
728x90
반응형