0

I am making a simple wpf application. It has a button and a textbox and when you click the button it should update the textbox the whole time(see code). I have 3 problems:

  1. It doesn't update the textbox in the loop.
  2. When I click the button It is stuck and I can't close the application(only with taskmanager and stop debugging).
  3. If i leave the textbox stuck and do not close it. After a minute or so I get this error: ContextSwitchDeadlock occurred with the break mode screen.

I have tried to solve the problem by searching on the internet but I didn't succeed. I hope you guys are able to solve it:). And the code is here:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Play_Click(object sender, RoutedEventArgs e)
    {
        int x = RandomNumber();
    }

    private string TextboxData;
    private int RandomNumber()
    {
        int x = 0;
        int i = 0;
        Random rng = new Random();
        do
        {
            x = rng.Next(1, 1000000);
            i++;
            TextboxData += "\r\nAl zo vaak :O" + i; //the rng loop
            textBox.Text = TextboxData;                
        }
        while (x != 1);
        TextboxData += "\r\nHij heeft zo vaak geprobeerd 1 te halen " + i;
        textBox.Text = TextboxData + Environment.NewLine;
        return x;
    }       
}
9
  • What is TextboxData, just a string? Commented Sep 15, 2015 at 6:32
  • @KevinKal it's declared before RandomNumber method: private string TextboxData; Commented Sep 15, 2015 at 6:33
  • Ohlol, I'm stupid. Anyway, there is a really low chance x becomes 1. So your program basically spams the chatbox pretty fast. Why don't you just textBox.AppendText ? Commented Sep 15, 2015 at 6:34
  • I made this program for a friend that is always with his calculator trying to get 1 with a chance for 1 to a million :P. It worked with console application but I wanted an interface Commented Sep 15, 2015 at 6:38
  • one advice - Always use stringBuilder when it comes to huge concatenation !!!!! Commented Sep 15, 2015 at 6:39

1 Answer 1

2

The problem is that all your actions are made in main GUI thread. That means that your program can't redraw interface because it's busy executing code in loop.

In order to achieve desired results you need to execute your loop asynchronous. But we must keep in mind that GUI should be updated only from GUI thread( it's framework requirement).

Due to quick calculations the texbox will be updated too often. You may consider using Thread.Sleep(100).

Here's solution:

    private async void Play_Click(object sender, RoutedEventArgs e)
    {
        int x = await RandomNumber();
    }

    private async Task<int> RandomNumber()
        {
            int x = 0;
            int i = 0;
            string text = string.Empty;
            Random rng = new Random();

            // This will start work in background. Leaving GUI thread to it's own tasks.
            await Task.Factory.StartNew(() =>
            {
                do
                {
                    x = rng.Next(1, 1000000);
                    i++;
                    text = "\r\nAl zo vaak :O" + i.ToString(); //the rng loop

                    // This will invoke textbox update in GUI thread satisfying update requirement.
                    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Input,
                        new Action(() => {  textBox.AppendText(text); }));

                    // We will make it slower in order to see updates at adequate rate.
                    Thread.Sleep(100);
                }
                while (x != 1);    
            }); 

            // thanks to await we will have this code executed after we found our x==1.
            text = "\r\nHij heeft zo vaak geprobeerd 1 te halen " + i;

            textBox.AppendText(text);
            return x;
        } 

Don't forget to add following usings:

using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;

EDIT: I don't know why you want to have return value from RandomNumber() (it will always be 1. so it's pontless). But to handle that correctly we need to add async to our signatures in order to use await so we could get a value, execute code after awaited block and return result.

It's a pretty complicated topic, which I will only mention here in order to have correct solution. If you're interested - google '.net async await'. But I suggest to leave it for future :)

Also, I removed TextBoxData field and replaced it with local variable and used textbox.AppendText() as @KevinKal suggested.

10
  • I will try this immediately when I am out of school(around 15.30) Commented Sep 15, 2015 at 7:13
  • If I make the method void do I still need to add that async thing? Commented Sep 15, 2015 at 11:02
  • The only thing that async do is enable usage of await. If you want void method with async, then you should declare it return type as Task. In serious projects it's not recommended to have async Task methods. They're allowed only for event handlers(such as Play_Click). But in your case I don't think that you should care now :) So you can just declare your RandomNumber as private async Task RandomNumber(). You need here async, because without await your last appendage to textbox won't work properly. Commented Sep 15, 2015 at 12:01
  • I will have a look now Commented Sep 15, 2015 at 14:44
  • got an error that says it returns the wrong type here is the exact discription: Severity Code Description Project File Line Error CS0407 'Task MainWindow.Play_Click(object, RoutedEventArgs)' has the wrong return type MaxenJorisfrustratie(met gui)again C:\Documenten\wouter\Csharp\C# visual studio apps\MaxenJorisfrustratie(met gui)again\MaxenJorisfrustratie(met gui)again\obj\Debug\MainWindow.g.i.cs\..\..\MainWindow.xaml 11 Commented Sep 15, 2015 at 14:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.