I get the error:

The calling thread cannot access this object because a different thread owns it.

when I use this code:

private async void onGetFilesAsync(object sender, RoutedEventArgs e)
{
    if (txtIpAddress.Text.Contains("IP Address"))
    {
        MessageBox.Show("Ip Address is invalid");
        return;
    } else if (string.IsNullOrEmpty(dpDate.Text))
    {
        MessageBox.Show("Date is invalid");
        return;
    }

    var date = dpDate.Text;
    var splitDate = date.Split('/');
    int month = Convert.ToInt32(splitDate[1]);
    int day = Convert.ToInt32(splitDate[0]);
    var year = splitDate[2];
    var filePath = [email protected]"\\{txtIpAddress.Text}\i\Hardware Interfacing\{year}\{month}\{day}\PeripheralLogsDq.txt";

    using (new ImpersonateUser("usernam", "", "password"))
    {
        FlowDocument doc = new FlowDocument();

        IsWaveActive = true;

        await Task.Run(() =>
        {
            LoadLogs(rbQueue, File.ReadAllText(filePath));
        });

        IsWaveActive = false;
    } 

private void LoadLogs(RichTextBox rtb, string msg)
{
    FlowDocument flowDocument = new FlowDocument();
    Paragraph paragraph = new Paragraph();
    paragraph.Inlines.Add(new Run(msg));
    flowDocument.Blocks.Add(paragraph);


    Dispatcher.Invoke(new Action(delegate ()
    {
        rtb.Document = flowDocument;
    }));
}

I am doing this because I am trying to implement a spinner when the data is loading from a text file.

1 Answers

2
Community On Best Solutions

The other thread comes form using Task.Run

    await Task.Run(() =>
    {
        LoadLogs(rbQueue, File.ReadAllText(filePath));
    });

replace it with something like:

using (var reader = File.OpenText(filePath))
{
    LoadLogs(rbQueue, await reader.ReadToEndAsync());
}

and then LoadLogs() does not need to Invoke anymore.