Trying to understand tasks in .net

Ok, I was busy with tasks in .net 4.5, and I'm trying to figure it out, so I created a small application that does some work, and I have a few questions about this.

Here is the code:

Account Controller.cs:

namespace MvcApplication1.Controllers { public class AccountController : Controller { private readonly UserManager _manager; public AccountController() { _manager = new UserManager(ContextFactory.GetContext()); } [HttpPost] public async Task<ActionResult> Register(LoginModel model) { var user = await _manager.FindAsync(model.UserName); if (user != null) { //do some work } else { ModelState.AddModelError("", "Cannot Find User"); return View(model); } } } } 

User Manager.cs:

  namespace MvcApplication1 { public class UserManager { private readonly IDBContext _context; public UserManager(IDBContext context) { _context = context; } public Task<UserProfile> FindAsync(string ID) { var queryHelper = new UserQueries(_context); var localID = ID; return Task.Factory.StartNew(() => queryHelper.GetProfile(localID)); } } } 

UserQueries.cs:

 public class UserQueries { private readonly IDBContext _context; public UserQueries(IDBContext context) { _context = context; } public UserProfile GetProfile(string ID){ DataTable dt = _context.ExecuteDataTable(...) //do work with dt and return UserProfile } } } 

IDBContext.cs

 public interface IDBContext { DataTable ExecuteDataTable(string sql, IEnumerable<SqlParameter> parameters); } 

So, I have a few questions.

Should I create a new instance of the UserQuery class in each function? Not sure if it should be synchronized or not, still messed up there.

Do I need to copy the identifier to localID, I'm worried about viewing and changing links when calling a function, is this something I can worry about anyway?

Should UserQueries be Task<UserProfile> ?

If UserQueries should be Task<UserProfile> , should the DBC text returning a DataTable also Task<DataTable> , does .net have a function for called SQL calls?

I am not 100% sure how deeply you work with Task

+7
source share
1 answer

if ExecuteDataTable does not have a built-in version of Async, I would recommend not using Tasks. If you need to use Task.Factory.StartNew or Task.Run to make it work, you probably won’t do this, and you will get worse performance under load than you leave it synchronous.

Task.Run (and Task.Factory.StartNew ) should only be used if you are expecting a CPU task to complete . ExecuteDataTable - I / O operation, you are waiting for a database response, any API that you use to communicate with the database can expose functions that return Task and those that you might expect (and you will need to await all the way up the call chain to the first call), but if it does not expose a function that returns Task , you should just do it in the usual way.

+7
source share

All Articles