uwpautosavefileloadexceptionricheditbox

How to autosave RichEditBox text?


I tried FileIO.WriteTextAsync(); with many events including Grid.Loaded and RichEditBox.TextChanged, but that method is asynchronous and conflicts with process called previous cycle. As a result, System.IO.FileLoadException with following description:

The process cannot access the file because it is being used by another process.

So what can I do in this case?


Solution

  • The TextChanged event is fired too frequently - you can type several characters in a second - handling the TextChanged event is too heavy for the UI thread.

    You can do this save operation in a Timer Tick event handler, set an Interval long enough to ensure the operation is completed before the next Tick occurs.

    DispatcherTimer timer; 
    
    public MainPage()
    {
        this.InitializeComponent();
    
        timer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(10) };
        timer.Tick += Timer_Tick;
        timer.Start();
    }
    
    private async void Timer_Tick(object sender, object e)
    {
        await FileIO.WriteTextAsync(file, tbInput.Text);
    }