Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

When a device has a plenty of memory, the difference can’t be seen in the naked eye.

What async and


await keywords do in a program is it lets the functions of the program to run asynchronously, meaning
the function will still run but in the background, making the program “faster”. The additional changes in
the code lets the database operations run in the background, freeing up memory for other tasks.

using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MauiApp6.Models;

namespace MauiApp6
{
public class StudentRepository
{
string _dbPath;

public string StatusMessage { get; set; }

private SQLiteAsyncConnection conn; // Changed to SQLiteAsyncConnection

private async Task Init() // Added async modifier and changed return type
{
if (conn != null)
return;

conn = new SQLiteAsyncConnection(_dbPath);


await conn.CreateTableAsync<Student>();
}

public StudentRepository(string dbPath)


{
_dbPath = dbPath;
}

public async Task AddNewStudent(string name)


{
int result = 0;
try
{
await Init();

if (string.IsNullOrEmpty(name))
throw new Exception("Valid name required");

result = await conn.InsertAsync(new Student { Name = name });

StatusMessage = string.Format("Record added (Name: {1})", result, name);


}
catch (Exception ex)
{
StatusMessage = string.Format("Failed to add {0}. Error: {1}", name, ex.Message);
}
}
public async Task <List<Student>> GetSection()
{
try
{
Init();
return await conn.Table<Student>().ToListAsync();
}
catch (Exception ex)
{
StatusMessage = string.Format("Failed to retrieve data. {0}", ex.Message);
}

return new List<Student>();


}
}
}

using MauiApp6.Models;

namespace MauiApp6
{
public partial class MainPage : ContentPage
{

public MainPage()
{
InitializeComponent();
}

private async void OnNewButtonClicked(object sender, EventArgs e)


{
statusMessage.Text = "";
await App.StudentRepo.AddNewStudent(newStudent.Text);
statusMessage.Text = App.StudentRepo.StatusMessage;

}
private async void OnGetButtonClicked(object sender, EventArgs e)
{
statusMessage.Text = "";
List<Student> section = await App.StudentRepo.GetSection();
sectionList.ItemsSource = section;

}
}

You might also like