728x90

razor 파일에서 IDisposable 을 이용해 화면을 벗어난 경우 Dispose 이벤트 처리하는 방법입니다.
razor 파일에서 @implements IDisposable 를 정의한 후 @code 단에서 아래 코드를 정의하면

    public void Dispose()
    {

    }

다른 화면으로 넘어간 경우 Dispose 메서드를 타게 됩니다.

@page "/fetchdata"

<PageTitle>Weather forecast</PageTitle>

@using Blazor.AppTest.Data
@inject WeatherForecastService ForecastService

@implements IDisposable

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from a service.</p>

<h5>Search Summary</h5>
<Search OnSearchChanged="SearchData" />

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
    <div class="spinner"></div>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Date</th>
                <th>Temp. (C)</th>
                <th>Temp. (F)</th>
                <th>Summary</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in forecasts)
            {
                <tr>
                    <td>@forecast.Date.ToShortDateString()</td>
                    <td>@forecast.TemperatureC</td>
                    <td>@forecast.TemperatureF</td>
                    <td>@forecast.Summary</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    private WeatherForecast[]? originForecasts;
    private WeatherForecast[]? forecasts;

    protected override async Task OnInitializedAsync()
    {
        // 데이터 비동기 처리
        await Task.Run(LoadData);
    }

    private async void LoadData()
    {
        // Test Sleep
        System.Threading.Thread.Sleep(2000);
        originForecasts = await ForecastService.GetForecastAsync(DateTime.Now);
        forecasts = originForecasts.ToArray();
    }

    private void SearchData(string searchText)
    {
        forecasts = originForecasts?.Where(c => c.Summary.ToUpper().Contains(searchText.ToUpper())).ToArray();
    }

    // IDisposable 처리
    public void Dispose()
    {
        originForecasts = null;
    }
}


[Source Code]
https://github.com/kei-soft/Blazor.AppTest

 

GitHub - kei-soft/Blazor.AppTest

Contribute to kei-soft/Blazor.AppTest development by creating an account on GitHub.

github.com

 

728x90
Posted by kjun.kr
,