ProgressWithAsyncAwait.zip
0.01MB
MainWindow.xaml
<Window x:Class="ProgressWithAsyncAwait.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ProgressWithAsyncAwait"
mc:Ignorable="d"
Title="Progress with Async Await" Height="300" Width="400">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<ProgressBar x:Name="progressBar" Height="30" Width="300"/>
<TextBlock x:Name="textBlock" Text="Start" FontSize="48" Margin="20" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button Width="300" Height="50" Content="Loop Through Number" FontSize="22" FontWeight="Bold" Click="Button_Click"/>
</StackPanel>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ProgressWithAsyncAwait
{
/// <summary>
/// MainWindow.xaml에 대한 상호 작용 논리
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var progress = new Progress<int>(value =>
{
progressBar.Value = value;
textBlock.Text = $"{value}%";
});
await Task.Run(() => LoopThroghNumbers(100, progress));
textBlock.Text = "Completed";
}
void LoopThroghNumbers(int count, IProgress<int> progress)
{
for (int x = 0; x < count; x++)
{
Thread.Sleep(100);
var percentComplete = (x * 100) / count;
progress.Report(percentComplete);
}
}
}
}
Do not use Task.Run in the implementation of the method, instead, use Task.Run to call the method.
- 시간이 오래 걸리는 메서드를 만들어 async/await 기능을 사용할때, 메서드 내부에서 Task.Run 을 사용하면 안된다.
- 시간이 오래 걸리는 메서들를 호출하는 쪽에서 Task.Run 을 사용하여 메서드를 호출해야 한다.
https://www.youtube.com/watch?v=zQMNFEz5IVU
'C# > C# WPF' 카테고리의 다른 글
PrismMVVMLibrary (0) | 2022.09.12 |
---|---|
Button 비활성화 상태에서 클릭 처리 (0) | 2022.08.20 |
View - ViewModel 바인딩 이름 (0) | 2022.08.15 |
Prism Template Pack (0) | 2022.08.15 |
Timer (0) | 2022.07.29 |