Cristian Lehuede Lyon
Cristian Lehuede Lyon

Reputation: 1947

Thread Starts lags UI WPF

Well, I've been struggling with this for a while and I've been unable to find a solution. I'm developing one of those cashier apps you see in the supermarket where everything works fast as hell. The cashiers know the program so good they just type at the speed of light so the UI must be incredibly responsive.

Anyway, as I've only coded in WPF I'm using it, if someone says WinForms is faster I'll surely learn it. This is my code, it's very simple as I'm testing performance

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

    private void Button_Click(object sender, RoutedEventArgs e)
    {

        t = new Thread(HandleThread);
        t.Start();
    }

    private void HandleThread()
    {
        Thread.Sleep(3000);
    }
}

Whenever the button is clicked, a new thread is launched as I plan on connecting to a server in the new thread. My problem is the method button_Click is VERY SLOW. It takes about 1 second to return so the button looks like it's stuck and the application look sluggish. I've tried threads, BackgroundWorker, changed the framework to 4.0 and tried Tasks. NOTHING. Whatever I do to start some kind of background work the method takes forever.

I need to check the username and password on a remote server, how can I accomplish it without hurting the UI?

Upvotes: 2

Views: 1078

Answers (2)

Florian Doyon
Florian Doyon

Reputation: 4186

Do you need to spawn a new thread every time you click your button? Is this thread long-lived? Do you really want to allocate 1 meg of stack space (on 64 bit OSes) for this every time you click this button? Really sure you don't want to use the TPL's Task and CancellationTokenSource instead?

In your case, you should really not create a thread every time you click, what you want is start a long-running async task and check the result.

public void OnClick(object src,EventArgs args)
{
    var login = tbLogin.Text;// assuming non MVVM coding here
    var pwd= tbPass.Text;
    Task.Factory.StartNew(()=>{
        return _myWebService.CheckAuth(login,pwd); // your login stuff here
    }).ContinueWith(wsTask=>{
       if(!wsTask.IsCompleted){ // handle errors / cancel }
       DisplayLoginState(ws.Result);
    }, TaskScheduler.FromCurrentSynchronizationContext()); // this runs on the UI Thread

}

Upvotes: 1

AgentFire
AgentFire

Reputation: 9780

You should turn off the IntelliTrace (How-To).

  1. On the Tools menu, click Options.
  2. In the Options dialog box, expand the IntelliTrace node and then click General.
  3. Clear the Enable IntelliTrace check box.
  4. Click OK.

Upvotes: 4

Related Questions