What is the better way to implement a C# thread to process functions to get data on database without lock user interface

StackOverflow https://stackoverflow.com/questions/23685247

Pregunta

I have a layered application. The GUI layer clicking a button, calls my business layer that calls a method from the data layer to access the database and bring a list of users.

How to call the data layer methods without locking the GUI with the User.

The methods of the data layer must receive parameters and return parameters.

For example: List all active users in the database.

IEnumerable <users> lstUsr = db.ListUsers(bool isActive);
¿Fue útil?

Solución

Rather than incurring the cost of thread management, let the task parallel library do this for you:

protected void SomeButton_OnClick(Object sender, EventArgs e)
{
    // A new task is not necessarily a new thread!
    Task.Factory.StartNew(() => PopulateSomeControl());
}

private async Task RequestDataAndPopulateTheControl()
{
    Statusbar.Text = "Loading from DB...";

    // this blocks only this method, not the UI thread.
    var data = await RequestData();

    // data is now available
    foreach(var whatever in data.ToList())
        SomeControl.Items.Add(whatever);

    Statusbar.Text = "Ready.";
}

private async Task<DataTable> RequestData()
{
    var db = new YourDbContext();

    return db.SomeDbSet().ToDataTable();
}

The method RequestDataAndPopulateTheControl() now becomes a readable union of your asynchronous threaded request for data as well as the callback to use the data. The UI thread is not blocked.

Otros consejos

As your tag indicates, spin up a thread! You just need to be mindful of needing Dispatcher.BeginInvoke to put the UI piece back on the UI thread when you are done.

new Thread(() => 
{
   IEnumerable<User> lstUsr = db.ListUsers(isActive);
   Distpatcher.BeginInvoke(() => 
   {
      myUiVariable = lstUsr;
   }
}

If you have access to an async Data Access Layer and are in .NET 4.0+, you can take advantage of async/await

myUiVariable = await db.ListUsersAsync(isActive);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top