-1

I am trying to update the UI form different class which is inside a thread.

Relevant code is:

MainWindow.xaml.cs

private void encryptButtonPressed(object sender, RoutedEventArgs e)
{
    if (checkValues() == true)
    {
        updateConsole("Starting Encryption...");

        Thread encryptThread = new Thread(encrypt);
        encryptThread.Start();
    }
}

encrypt function

public void encrypt()
{
    Encrypt encrypt = new Encrypt(this.KeyFileContent, this.SourcePath, this.DestinationPath, this);
    encrypt.start();
}

update console function

public void updateConsole(String text)
{
    consoleWindow.AppendText(Environment.NewLine);
    consoleWindow.AppendText(text);

    consoleWindow.ScrollToEnd();
}

Encrypt.cs

public byte[] key;
public String source;
public String destination;
public MainWindow mainWindow;

public Encrypt(byte[] key, String source, String destination, MainWindow mainWindow) 
{
    this.key = key;
    this.source = source;
    this.destination = destination;
    this.mainWindow = mainWindow;
}

start function

public void start()
{
    mainWindow.updateConsole("Updating form thread");
}

I have tried

Dispatcher.Invoke(() =>
    {
        mainWindow.updateConsole("Updating form thread");
    });

but no use.

croxy
  • 4,082
  • 9
  • 28
  • 46
Eirtaza
  • 137
  • 2
  • 16

1 Answers1

1

Instead of injecting the whole mainWindow you should be only pass in the stuff you need. In this case the updateConsole method.

change the start method to this:

public void start(Action<string> updateConsole)
{
    updateConsole.Invoke("Updating form thread");
}

then you should be able to make pass in the method like this:

public void encrypt()
{
    Encrypt encrypt = new Encrypt(this.KeyFileContent, this.SourcePath, this.DestinationPath, this);
    start(updateConsole);
}

Lastly you don't need to inject in the mainWindow to your Encrypt class any longer:

public byte[] key;
public String source;
public String destination;

public Encrypt(byte[] key, String source, String destination) 
{
    this.key = key;
    this.source = source;
    this.destination = destination;
}
Mike
  • 850
  • 10
  • 33
  • It is an elaborate solution but for time being, my code is running :) . I will keep it for future reference. Thanks :) – Eirtaza Apr 26 '18 at 12:27
  • Also i noticed you don't use databinding to your `consoleWindow`. Maybe you should read into MVVM if this is a larger project :-) [MVVM](https://stackoverflow.com/questions/1405739/mvvm-tutorial-from-start-to-finish) – Mike Apr 26 '18 at 12:31
  • this is just a small project. Thanks for ur suggestion :) – Eirtaza Apr 26 '18 at 12:54
  • plus i am beginner – Eirtaza Apr 26 '18 at 12:58