How to make async with linq

i'm trying to make my first web application with asp.net mvc including remote database with linq. So i'm using default template from mvc, i've remade code in AccountController that implement register users with using linq, and now i'm interesting do it with async. So is it possible to handle linq with async? And if it yes, show me please example how to do that, it will be very helpful for me. Here's my example of registration via linq:

[AllowAnonymous] public ActionResult Register() { return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult Register(RegisterViewModel model) { if (ModelState.IsValid) { using (DataBaseClassDataContext dc = new DataBaseClassDataContext()) { Users tbUsers = new Users(); tbUsers.Login = model.Login; tbUsers.Name = model.Name; tbUsers.Surname = model.Surname; tbUsers.Password = model.Password; tbUsers.E_Mail = model.Email; tbUsers.Knowledge = model.Knowledge; dc.Users.InsertOnSubmit(tbUsers); dc.SubmitChanges(); ModelState.Clear(); ViewBag.Message = "Successfully Registration Done"; } } // If we got this far, something failed, redisplay form return View(model); }

--------------Solutions-------------

Let's look at your first action first:

[AllowAnonymous]
public ActionResult Register()
{
return View();
}

Well, there's nothing here that does anything that would delay the current thread, so there's no benefit in doing anything asynchronously, so the best thing to do is to just leave this one alone.

Now, let's look at your second action. It contains:

dc.SubmitChanges();

That does indeed block the current thread while the changes are sent to the database. It probably won't be a big hit, but it is somewhere where we might benefit from using asynchronous code, especially because it's just so darn easy to do these days.

First change the signature:

public async Task<ActionResult> Register(RegisterViewModel model)

If you compile now it will work, but you'll get a warning:

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

But we've already done two things:

  1. Changed from returning ActionResult to returning Task<ActionResult>.
  2. Used async to mean that we can just do return View(model); and it gets turned into code that actually returns a Task<ActionResult> that when run will then run code like that in your original method.

But we've not actually gained anything. However instead of dc.SubmitChanges() we'll use dc.SubmitChangesAsync().

This is assuming it exists, which will depend on your data provider. More on that in a bit.

If it does exist then instead of returning void or some value T it would return Task or Task<T>.

We could write code to handle that task ourselves, but the easiest thing to do is:

await dc.SubmitChangesAsync();

Now the method we have is one that returns a Task<Action> that when initially Run (MVC will handle that bit for us) will execute the code as far as that await. Then it will release the thread running the code to do other things. After the SubmitChangesAsync has done its job, the execution of the method resumes at that point.

Similarly we could turn a method like:

var someList = someQuery.ToList();

Into:

var someList = await someQuery.ToListAsync();

Now, as I said, this all depends on the methods which result in database access actually having an async version. If there is no SubmitChangesAsync() then either you have to give up on this approach (boo!) or you have to write your own implementation (not trivial).

The current version of EntityFramework provides the following:

AllAsync
AnyAsync
AverageAsync
ContainsAsync
CountAsync
FirstAsync
FirstOrDefaultAsync
ForEachAsync
LoadAsync
LongCountAsync
MaxAsync
MinAsync
SingleAsync
SingleOrDefaultAsync
SumAsync
ToArrayAsync
ToDictionaryAsync
ToListAsync
SaveChangesAsync

That is, pretty much all of the methods that result in an actual database access have an Async version.

If you are not using a provider which offers this, then moving to asynchronous code will not be easy; it'll involve a more than can be put into a quick answer to do well.

One final caveat. Say you have an async method that always does a single await and that await is a tail-call:

public async Task<List<int>> GetList(int typeID)
{
if(typeID < 1)
throw new ArgumentOutOfRangeException();
return await (from stuff in place where stuff.TypeID == typeID select stuff).ToListAsync();
}

Here you should not use async and await at all, because you are creating a task which will always result in a single task being awaited on, and so the extra await just complicates things behind the scenes for no good reason. Here you should just return the task:

public Task<List<int>> GetList(int typeID)
{
if(typeID < 1)
throw new ArgumentOutOfRangeException();
return (from stuff in place where stuff.TypeID == typeID select stuff).ToListAsync();
}

But note that something that looks like a tail call inside a using block is not really a tail call, because it also implicitly does the Dispose() at the end of the using, so you can't simplify such calls in that way.

You can though simplify cases where there are different possible tail calls, as long as every path either does such a call, or throws an exception:

public async Task<List<int>> GetList(int? typeID)
{
if(!typeID.HasValue)
throw new ArgumentNullException();
if(typeID.Value < 0)
return await (from stuff in place).ToListAsync();
return await (from stuff in place where stuff.TypeID == typeID select stuff).ToListAsync();
}

Can become:

public Task<List<int>> GetList(int? typeID)
{
if(!typeID.HasValue)
throw new ArgumentNullException();
if(typeID.Value < 0)
return (from stuff in place).ToListAsync();
return (from stuff in place where stuff.TypeID == typeID select stuff).ToListAsync();
}

Category:c# Time:2018-06-10 Views:0

Related post

  • How to make async method call inside of another async `each` method (NodeJS)? 2012-01-13

    How to make async method call inside of another async each method (NodeJS)? Concrete example - working with a database, I need to delete all records. But I can't just drop the whole collection, I need to destroy every record one by one, before deleti

  • Should I teach CSS layout directly to new learners or should I first teach how to make layout with tables, then table-less layouts? 2010-01-27

    Should I teach CSS layout directly to new learners or should I first teach how to make layout with tables, then div+CSS? And what should I teach between HTML or XHTML? Both are same so should I start directly with XHTML 1.0 Strict? --------------Solu

  • How to get started with Linq to sql? 2010-02-02

    I am developing a new web application which would be simple and i decided to use asp.net mvc and Linq to sql.. I thus far have no idea about Linq to Sql... How to get started with Linq to sql? What should i watch out for when using Linq to sql? -----

  • How to make a object moving - How to make game with VB.NET 2010-07-22

    How to make a object moving on the screen- How to make game with VB.NET - In 2d game, ex i see a mario charator, which is object ( Label, image v.v.v) - Is there a physical engine for vb.net Sorry, bad english --------------Solutions------------- You

  • How to make this with htacess? 2012-02-13

    How to make this with htacess: http://domain.com/category => /index.php?action=category http://domain.com/category?query=string => /index.php?action=category&query=string http://domain.com/category/subcategory => /index.php?action=catego

  • How to make partition with Windows 7 starter 2014-11-18

    Can someone tell me how to make partition with Windows 7 starter? I hit the error below after trying to create new partition with Disk Management: "Dynamic disks are not supported by this operation system or server configuration. Dynamic disks are no

  • How to retrieve data with LINQ to SQL into a weakly-typed object that can be moved around 2009-07-01

    In classic ASP we had the record set object. With ADO.Net we had the datatable. Both were simple .Net objects that could be moved around easily. What is the equivalent for using LINQ To SQL? Most examples show "var" being used, however, this seems co

  • Some basic questions on database design and how to insert accordingly with LINQ to Entities 2011-05-24

    Ok, I am total newbie so bear with me. Trying to implement an ordering system and wish to save the orders to the database with LINQ to Entities. I can do it now but for each new object that is saved to the orders table a new row is inserted, with new

  • how to make webpage with gzip? 2009-06-26

    Yslow and google are recommending gzip for webpages. but I am not able to find how to make web pages with gzip. Can anyone direct me to any tutorials or explain how to do it? Thanks in advance. --------------Solutions------------- You don't make a pa

  • how to make table with jquery? 2010-06-22

    hai.all..can you tell me how to make table in jquery? i want using this plugin for showing all data which have been input from database.. i use SELECT * FROM inspection_report for showing data table inside process.php file... how to combine with it??

  • How can I update with LINQ all records that have equal value? 2010-08-19

    Can anybody help me with this: I want select all records from datatable which have for example sid=123 and after that save they with sid=456. How can I do this with LINQ? --------------Solutions------------- items.Where(i=>i.sid == 123).ToList().F

  • How update full object with linq to entities? 2010-11-17

    I want update object with linq to entities, like this : public ActionResult SubmitPool(SwimmingPool Pool) { SwimmingPool IsPool = (from sp in db.SwimmingPool where sp.Id == Pool.Id select sp).First(); if (IsPool != null) { IsPool = Pool; db.SaveChang

  • How to make validation with Jquery if there is ACTION within form? 2011-01-14

    I have tested the following validation script: jQuery validation plug-in 1.7 How to make working validation error as I have to use action="" Is there possibility as error is not working in this case. Where is set id="cname" name="name" within validat

  • How to map component with linq to sql? 2011-01-14

    I have two classes. I want to map Class1 to a database table with linq to sql. [Table(Name = "SomeTable")] public class Class1 { public Class2 Class2 { get; set; } } class Class2 { public string Name1 { get; set; } public string Name2 { get; set; } p

  • Android: How to make AlertDialog with 2 Text Lines and RadioButton (Single Choice)? 2011-03-17

    How to make a List Dialog with rows like this: |-----------------------------| | FIRST LINE OF TEXT (o) | <- this is a "RadioButton" | second line of text | |-----------------------------| I know I should use a custom adapter, passing a row layout

  • How to parse xml with Linq? 2011-04-27

    Hi I have xml string like you can see below <?xml version="1.0" encoding="ISO-8859-1" ?> - <Result> - <AllItems> - <Item attribute="123"> <SubItem subAttribute="1" /> <SubItem2 subAttribute2="2" /> </Item> -

  • How to make layout with View fill the remaining space? 2011-06-11

    I'm designing my application UI. I need a layout looks like this: (< and > are Buttons). The problem is, I don't know how to make sure the TextView will fill the remaining space, with two buttons have fixed size. If I use fill_parent for Text V

  • How to make QScrollBar with fixed size handle? 2011-10-10

    I have to make scrollbar with handle of fixed size since its background image becomes ugly when being scaled. I use the following style sheet: QScrollBar::handle:vertical { border-image:url(:/images/handle.png); min-height: 47px; max-height: 47px; he

  • How to query collection with Linq.Expressions 2012-01-16

    I built a custom IQueryable provider. The provider transforms query for example c.PurchaseDate == new DateTime(2011, 11, 29) && c.Name == "Elizabeth Brown" from underlying code into System.Linq.Expressions.Expression Now I need to run them ag

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.562 (s). 13 q(s)