Reputation: 1947
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
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