Task<T>.Factory.StartNew in ASP.NET MVC - c#

I'm stuck with a problem. I need help...
In general, I have an ASP.NET MVC 5 project. When a user clicks on "Save" button, I run some code in a new created task. I need to know the result of operation, so I return the instance of my class ChangesMade. Then I serialze the object to JSON format and pass to a view. Then I check if result is true, I open an url in a new window.
So, in my controller I have the following:
public async Task<ActionResult> Save(here some parameters)
{
var changes = await _model.SaveAsync(some parameters);
return NewtownJson(changes);
}
The main saving logic is the following:
public async Task<ChangesMade> SaveAsync(some parameters here)
{
var data = (await _model.GetData(some parameter)).ToList();
// create a task of ChangesMade that contains public bool property MemoAdded
// that I need to pass to a view to know the result of operation
var task = Task<ChangesMade>.Factory.StartNew(() =>
{
ChangesMade changes = new ChangesMade();
try
{
using (var tr = new TransactionScope())
{
// some code here omitted for simplicity…
// if (someCondition == true) changes.MemoAdded = true;
tr.Complete();
}
return changes;
}
catch (Exception ex)
{
throw ex;
}
});
try
{
task.Wait();
}
catch (AggregateException ex)
{
string msg = "";
msg= ex.Flatten().InnerExceptions
.Where(e => e != null)
.Select(e => e.Message)
.Aggregate(msg, (current, message) => current + " " + message + ";")
.TrimEnd(';');
throw new Exception(msg);
}
return task.Result;
}
I publish the project on two sites on IIS. The first works fine. But the second doesn't - by some reason, it always returns changes.MemoAdded false to the view.
I can't find out a reason of that. I don't have a clue what to do ...

Related

Running a thread in the background when controller return to UI with full results - async call of a function from Controller method

Hi I have Controller method as below
[HttpPost]
public JsonResult Post(string vehiclesString, string Entity, int EntityId, ApplicationUser CurrentUser)
{
//https://stackify.com/understanding-asp-net-performance-for-reading-incoming-data/
List<Vehicle> vehicles = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Vehicle>>(vehiclesString);
InputFieldController c = new InputFieldController();
var errors = new List<string>();
try
{
//let's get model for each of the input field
InputFieldController icController = new InputFieldController();
List<InputField> fields = icController.GetNamesValues("VehicleField", -1, "Vehicle", 0);
foreach (Vehicle vehicle in vehicles)
{
//convert array of strings into array of input fields
if (fields.Count != vehicle.ValueStrings.Count)
{
throw new Exception("Vehicle columns mismatch. Expected "
+ fields.Count + " fields, but received " + vehicle.ValueStrings.Count);
}
for (int i = 0; i < fields.Count; i++)
{
InputField field = fields[i];
string cell = vehicle.ValueStrings[i];
if ((cell != null || cell != String.Empty) && (field.Type == "radio" || field.Type == "dropdown"))
{
var f = field.InputDropdowns.Where(x => x.Name == cell).FirstOrDefault();
if (f != null)
{
field.InputValue.InputDropdownId = f.InputDropdownId;
}
else
field.InputValue.InputDropdownId = null;
}
else
{
field.InputValue.Value = cell;
}
vehicle.Values.Add(field);
}
vehicle.Blob = Newtonsoft.Json.JsonConvert.SerializeObject(vehicle.Values);
Vehicle v = new Vehicle();
if (vehicle.VehicleId == 0)
{
v = this.DomainLogicUnitOfWork.VehicleManager.Create(vehicle, Entity, EntityId);
}
}
JsonResult data = Json(new
{
success = true,
});
List<Vehicle> vehiclesList = this.DomainLogicUnitOfWork.VehicleManager.List(Entity, EntityId);
if (vehiclesList != null)
foreach (Vehicle v in vehiclesList)
{
if ((v != null) && (v.Blob != null))
v.Values = Newtonsoft.Json.JsonConvert.DeserializeObject<List<InputField>>(v.Blob);
}
//Task task = Task.Run(async () => await this.DomainLogicUnitOfWork.VehicleInfoManager.CreateOrUpdate(Entity, EntityId));
/*
* Here I have to call the this.DomainLogicUnitOfWork.VehicleInfoManager.CreateOrUpdate(string Entity, int EntityId) asynchronously
* but return the data without waiting for the CreateOrUpdate to complete
*/
System.Web.Hosting.HostingEnvironment.QueueBackgroundWorkItem(async cancellationToken =>
{
await this.DomainLogicUnitOfWork.VehicleInfoManager.CreateOrUpdate(vehiclesList, Entity, EntityId);
});
return data;
}
catch (Exception ex)
{
LogHandler.LogError(9000, "Error updating input fields", ex);
errors.Add("Error 9000:" + ex.Message);
return Json(new
{
error = ex.Message
});
}
}
And I have CreateOrUpdate method defined as below in VehicleInfoManager class
public async Task CreateOrUpdate(string Entity, int EntityId)
{
//do some stuff
var task = Task.Run(() => Test(Entity, EntityId));
//do other stuff
await task;
//some more stuff
}
And Test method is as follows
private void Test(string Entity, int EntityId)
{
List<VehicleInfo> addList; List<VehicleInfo> updateList;
try
{
this.GetAddAndUpdateList(Entity, EntityId, out addList, out updateList);
if ((addList != null) && (addList.Count > 0))
using (var cont = this.UnitOfWork.Context)
{
foreach (var a in addList)
{
cont.VehicleInfos.Add(a);
}
cont.SaveChanges();
}
if ((updateList != null) && (updateList.Count > 0))
using (var cont = this.UnitOfWork.Context)
{
foreach (var a in updateList)
{
var aa = cont.VehicleInfos?.Where(x => x.VehicleInfoId == a.VehicleInfoId)?.FirstOrDefault();
aa.Address_City = a.Address_City;
aa.Address_Country = a.Address_Country;
aa.Address_StateCode = a.Address_StateCode;
aa.Address_Street1 = a.Address_Street1;
aa.Address_Street2 = a.Address_Street2;
aa.Address_Zip = a.Address_Zip;
aa.ChassisYear = a.ChassisYear;
aa.EngineFamilyName = a.EngineFamilyName;
aa.Entity = a.Entity;
aa.EntityId = a.EntityId;
aa.InputFieldEntity = a.InputFieldEntity;
aa.InputFieldEntityId = a.InputFieldEntityId;
aa.InputFieldGroup = a.InputFieldGroup;
aa.LicensePlate = a.LicensePlate;
aa.Manufacturer = a.Manufacturer;
aa.ModelYear = a.ModelYear;
aa.PurchasedDate = a.PurchasedDate;
aa.RegHoldClearBy = a.RegHoldClearBy;
aa.RegHoldClearDate = a.RegHoldClearDate;
aa.RegHoldComment = a.RegHoldComment;
aa.RegHoldSet = a.RegHoldSet;
aa.RegHoldSetBy = a.RegHoldSetBy;
aa.RegHoldSetDate = a.RegHoldSetDate;
aa.TrailerPlate = a.TrailerPlate;
aa.UpdatedBy = a.UpdatedBy;
aa.UpdatedDate = a.UpdatedDate;
aa.VehicleId = a.VehicleId;
aa.VehicleOperator = a.VehicleOperator;
aa.VehicleOwner = a.VehicleOwner;
aa.VIN = a.VIN;
}
cont.SaveChanges();
}
}
catch (Exception ex)
{
ARB.Logging.LogHandler.LogError(9001, "CreateOrUpdate(string Entity, int EntityId) in class VehicleInfoManager", ex);
throw ex;
}
}
What I want is, I want two things here
the Post method to call or start the CreateOrUpdate method as background call but instead of waiting until the CreateOrUpdate method finishes, it should return the result data to UI and continue the big task CreateOrUpdate in the background.
Is there anyway to start the background method CreateOrUpdate after sometime like (10 mins etc) post method returns to UI, if it can't be done, its OK we don't have to worry but just asking if there is anyway to trigger this from within the same application
When I implemented it in the above way, even after using System.Web.Hosting.HostingEnvironment.QueueBackgroundWorkItem I am still getting the null http context at the following location
user = System.Web.HttpContext.Current.User.Identity.Name; url = System.Web.HttpContext.Current.Request.Url.ToString();
System.Web.HttpContext.Current is coming out as null.
and the application is breaking,
I chaned my async call to the following to use HostingEnvironment.QueueBackgroundWorkItem, still the same htt current context is coming out as null, any help please
System.Web.Hosting.HostingEnvironment.QueueBackgroundWorkItem(async cancellationToken =>
{
await this.DomainLogicUnitOfWork.VehicleInfoManager.CreateOrUpdate(Entity, EntityId);
});
Thank you
System.Web.HttpContext.Current is maintained by the ASP.NET's SynchronizationContext.
When you start a new Task, the code will be executing on another thread pool thread without a SynchronizationContext and the value of System.Web.HttpContext.Current is not safe to use, whatever its value.
When the execution of the action method (Post) ends, the request will end and the HttpContext instance will be invalid, even if you mange to get a reference to it.
Also, there is no guarantee that that code you posted to the thread pool will run to complete, since it's out of ASP.NET control and ASP.NET won't be aware of it if IIS decides, for some reason, to recycle the application pool or the web application.
If you to post background work, use HostingEnvironment.QueueBackgroundWorkItem. Beware if its constraints.

How to get parallel access to the method for multiple users

My telegram bot is necessary so that the user can answer questions in order and save these answers in the same order for a specific user in parallel.
static readonly ConcurrentDictionary<int, string[]> Answers = new ConcurrentDictionary<int, string[]>();
static void Main(string[] args)
{
try
{
Task t1 = CreateHostBuilder(args).Build().RunAsync();
Task t2 = BotOnMessage();
await Task.WhenAll(t1, t2);
}
catch (Exception ex)
{
Console.WriteLine("Error" + ex);
}
}
here is my BotOnMessage() method to receive and process messages from users
async static Task BotOnMessage()
{
int offset = 0;
int timeout = 0;
try
{
await bot.SetWebhookAsync("");
while (true)
{
var updates = await bot.GetUpdatesAsync(offset, timeout);
foreach (var update in updates)
{
var message = update.Message;
if (message.Text == "/start")
{
Registration(message.Chat.Id.ToString(), message.Chat.FirstName.ToString(), createdDateNoTime.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture));
var replyKeyboard = new ReplyKeyboardMarkup
{
Keyboard = new[]
{
new[]
{
new KeyboardButton("eng"),
new KeyboardButton("ger")
},
}
};
replyKeyboard.OneTimeKeyboard = true;
await bot.SendTextMessageAsync(message.Chat.Id, "choose language", replyMarkup: replyKeyboard);
}
switch (message.Text)
{
case "eng":
var replyKeyboardEN = new ReplyKeyboardMarkup
{
Keyboard = new[]
{
new[]
{
new KeyboardButton("choice1"),
new KeyboardButton("choice2")
},
}
};
replyKeyboardEN.OneTimeKeyboard = true;
await bot.SendTextMessageAsync(message.Chat.Id, "Enter choice", replyMarkup: replyKeyboardEN);
await AnonymEN();
break;
case "ger":
var replyKeyboardGR = new ReplyKeyboardMarkup
{
Keyboard = new[]
{
new[]
{
new KeyboardButton("choice1.1"),
new KeyboardButton("choice2.2")
},
}
};
replyKeyboardGR.OneTimeKeyboard = true;
await bot.SendTextMessageAsync(message.Chat.Id, "Enter choice", replyMarkup: replyKeyboardGR);
await AnonymGR();
break;
}
offset = update.Id + 1;
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error" + ex);
}
}
and AnonymEN() method for eng case in switch. The problem appears here when I call this method from switch case in BotOnMessage(). Until switch (message.Text) multiple users can asynchronously send messages and get response. When first user enters AnonymEN() second user can't get response from this method until first user will finish it till the end. Also I call BotOnMessage() in the end of AnonymEN() to get back for initial point with possibility to start bot again. For the ordered structure of questions and answers I used ConcurrentDictionary way from here Save user messages sent to bot and send finished form to other user. Any suggestion and solution how to edit code to make this bot available for multiple users at one time?
async static Task AnonymEN()
{
int offset = 0;
int timeout = 0;
try
{
await bot.SetWebhookAsync("");
while (true)
{
var updates = await bot.GetUpdatesAsync(offset, timeout);
foreach (var update in updates)
{
var message = update.Message;
int userId = (int)message.From.Id;
if (message.Type == MessageType.Text)
{
if (Answers.TryGetValue(userId, out string[] answers))
{
var title = message.Text;
if (answers[0] == null)
{
answers[0] = message.Text;
await bot.SendTextMessageAsync(message.Chat, "Enter age");
}
else
{
SaveMessage(message.Chat.Id.ToString(), "anonym", "anonym", "anonym", answers[0].ToString(), title.ToString(), createdDateNoTime.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture));
Answers.TryRemove(userId, out string[] _);
await bot.SendTextMessageAsync(message.Chat.Id, "ty for request click /start");
await BotOnMessage();
}
}
else if (message.Text == "choice1")
{
Answers.TryAdd(userId, new string[1]);
await bot.SendTextMessageAsync(message.Chat.Id, "Enter name");
}
}
offset = update.Id + 1;
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error" + ex);
}
}
I can see multiple issues with your code:
It is hard to read. While this is a personal preference I strongly advise to write short concise methods that have 1 responsibility. This will make it easier to understand and maintain your code. https://en.wikipedia.org/wiki/Single-responsibility_principle
Everything is static. This makes it very hard to keep track of any state such as language that should be tracked per user.
Using infinite loops and recursion with no escape. I highly doubt this was intended but you could get an infinite chain of calls like this BotOnMessage -> AnonymEN -> BotOnMessage -> AnonymEN. I think you want to exit the AnonymEN function using either a return, break or while(someVar) approach instead of calling the BotOnMessage function.
If two users are sending messages you get mixed responses. Example message flow user1: /start, user1: eng, user2: hello. The bot will now give an english response to user2. I'm sure this is not intended
The code below is a minimal example that addresses the issues I mentioned. It is not perfect code but should help you get started.
private Dictionaty<string, UserSession> userSessions = new ();
async Task BotOnMessage()
{
try
{
while(true)
{
var message = await GetMessage(timeout);
var userSession = GetUserSession(message.user);
userSession.ProcessMessage(message);
}
}
catch(){}
}
async void GetUserSession(string user)
{
if(!userSessions.HasKey(user))
{
userSessions[user](new Session());
}
return userSessions[user];
}
public class UserSession
{
public async Task ProcessMessage(message)
{
// Existing message processing code goes here.
// Do not use a loop or recursion.
// Instead track the state (e.g. languge) using fields.
}
}

Task<List<T>> returns List.Count=0 but has 116 Elements

I really don't know what the problem is. I've an win8.1 App which is calling a WCF Method for getting some Data. When i debug the WCF it returns a Task<List<T>> with List.Count=116 Elements in the List but when the List (Task) "arrives" in my App it always says List.Count=0.
Tested with WCF-Testclient too - result:
And the result i get in my Win8 App:
Call:
private List<Person> getPersonList()
{
IService client = CustomServiceBinding.GetClientForIService();
try
{
if (client != null && ((IClientChannel)client).State == CommunicationState.Opened))
{
var personList = client.GetPersonStateList(terminalName);
personList.Wait(Timeout.Infinite);
if (personList.IsCompleted)
{
if (personList.Result == null || personList.Result.Count <= 0)
{
// i'm ALWAYS landing here because the List has no Elements
// but when the method in the WCF returns the List had 116 Elements
// where do they get lost?
}
else
{
foreach (var item in personList.Result)
{
loginTextbox.Text += "Yeah";
}
}
}
}
}
catch (CommunicationObjectFaultedException cofe)
{
ExceptionHandling(cofe);
if (client != null)
{
((IClientChannel)client).Abort();
}
}
catch (Exception ex)
{
ExceptionHandling(ex);
if (client != null)
{
((IClientChannel)client).Abort();
}
}
finally
{
if (client != null)
{
((IClientChannel)client).Close();
((IClientChannel)client).Dispose();
}
}
}
Method in WCF:
public async Task<List<Person>> GetPersonStateList(string terminal)
{
Task<List<Person>> t = Task.Run(() =>
{
List<Person> personList = new List<Person>();
try
{
//calling another WCF - returns 116 Elements
//validatePerson always returns true (hardcoded for testing)
currentPersonList = ServiceBinding.getCurrentPersonList().GetPersonEnumeration().Where(x => validatePerson(x));
}
catch (Exception ex)
{
currentPersonList = null;
ExceptionContainer myException = new ExceptionContainer("Message: " + ex.Message);
throw new FaultException<ExceptionContainer>(myException);
}
if (currentPersonList != null && currentPersonList.Count() > 0)
{
foreach (var item in currentPersonList)
{
TimeSpan ts;
var dailyTimes = item.GetDailyTimeEnumeration();
foreach (var day in dailyTimes)
{
ts = new TimeSpan(0, 0, (int)day.RawValue);
personList.Add(new Person() { Name = item.firstname + " " + item.lastname, dailyTime = ts });
}
}
}
else
{
// i never get in here
personList = null;
}
// at this point the personList has 116 valid Elements
return personList;
});
// this "t" has a List with 116 Elements at the return point
return await t;
}
What am i missing here? Did i forget something? Do i have to lock something (if yes, WHAT should i lock and where?)?
** EDITED **
Added more code examples in WCF Method and two Screenshots from the results i get in WCF and in Win8 App.
** EDITED **
Now i've changed a few things in coding in the given methods above.
Second one is not returning a Task<List<Person>> but just a List<Person>.
The first Method is shortened and looks like this:
private async void updateUI(object sender, object e)
{
try
{
List<Person> list = new List<Person>();
TM2K_Service client = IAGServiceBinding.GetClientForTM2K();
try
{
if (client != null)
{
string terminalName = getTerminalName().ToLower();
// asynchronous
var personList = await client.GetPersonStateList(terminalName);
if (personList == null || personList.Count <= 0)
{
// BUT I'M STILL STUCK HERE WITH A LIST WITH ZERO ELEMENTS (Count=0)
}
else
{
foreach (var item in personList.Result)
{
loginTextbox.Text += "Yeah";
}
}
}
}
catch (Exception x)
{
ExceptionHandling(x);
}
}
catch (Exception ex)
{
ExceptionHandling(ex);
}
}
I get the same Results when i'm calling the IIS published WCF as when i call the WCF-Testclient var personList Count=0.
** EDIT **
I found out it's a problem with deserializing of collections or generic lists. When you add a servicereference via visual studio (clicking) it sets default collection types for deserialization. I'm working with ChannelFactory so i have to set it as KnownType(typeof)? But i'm fairly new to this niveau of coding in WCF or setting programmatically servicereferences on clientside - how and where do i set these attributes? And i tried the known type IList<> too or an Array or an ObservableCollection. No chance to deserialize received data.
How and which attributes do i have to set for deserialization?

Null values while updating DB in Parallel.Foreach

I use following script to get data from external service and store in dB. In certain rare cases less than 1% records gets updated with null values. In below code, the "re.status=fail" we see null. let us know if any thots.
public void ProcessEnquiries()
{
List<req> request = new List<req>();
var options = new ParallelOptions { MaxDegreeOfParallelism = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["MaxDegreeOfParallelism"]) };
try
{
Parallel.ForEach(request, options, currentRequest =>
{
ProcessedRequest processedRequest = null;
processedRequest = CommunicateToWS(currentRequest); // Here we call to webservice
});
}
catch (AggregateException exception)
{
foreach (Exception ex in exception.InnerExceptions)
{
// Handle Exception
}
}
}
public ProcessedRequest CommunicateToWS(req objReq)
{
ProcessedRequest re = new ProcessedRequest();
using (WebCall obj = new WebCall())
{
re.no = refnu;
try
{
retval = obj.getValue(inval);
objProxy.Close();
//get data
// parse and store to DB
}
catch (Exception e)
{
re.status = "fail";
//update DB that request has failed
//Handle Exception
obj.Close();
}
}
}

Returning Void in Async method from WEB API Controller

I have this async method inside ASP.NET MVC 4 WEB API Controller that I got from this blog:
http://www.strathweb.com/2012/04/html5-drag-and-drop-asynchronous-multi-file-upload-with-asp-net-webapi/
public async Task<IList<RecivedFile>> Post()
{
List<RecivedFile> result = new List<RecivedFile>();
if (Request.Content.IsMimeMultipartContent())
{
try
{
MultipartFormDataStreamProvider stream = new MultipartFormDataStreamProvider(HostingEnvironment.MapPath("~/USER-UPLOADS"));
IEnumerable<HttpContent> bodyparts = await Request.Content.ReadAsMultipartAsync(stream);
IDictionary<string, string> bodyPartFiles = stream.BodyPartFileNames;
IList<string> newFiles = new List<string>();
foreach (var item in bodyPartFiles)
{
var newName = string.Empty;
var file = new FileInfo(item.Value);
if (item.Key.Contains("\""))
newName = Path.Combine(file.Directory.ToString(), item.Key.Substring(1, item.Key.Length - 2));
else
newName = Path.Combine(file.Directory.ToString(), item.Key);
File.Move(file.FullName, newName);
newFiles.Add(newName);
}
var uploadedFiles = newFiles.Select(i =>
{
var fi = new FileInfo(i);
return new RecivedFile(fi.Name, fi.FullName, fi.Length);
}).ToList();
result.AddRange(uploadedFiles);
}
catch (Exception e)
{
}
}
return result;
}
My question is why exactly does this method have a return type of Task? It is not clear "where to" or "to whom" it returns this task? It's like there is no one that waits for/receives the returned object.
I wonder what will be the implications if I return void like this:
EDIT:
I have tried the code below and it completely breaks the program. it's like the runtime looses the reference to the code, the code itself doesn't finish running.
public async void Post()
{
List<RecivedFile> result = new List<RecivedFile>();
if (Request.Content.IsMimeMultipartContent())
{
try
{
MultipartFormDataStreamProvider stream = new MultipartFormDataStreamProvider(HostingEnvironment.MapPath("~/USER-UPLOADS"));
IEnumerable<HttpContent> bodyparts = await Request.Content.ReadAsMultipartAsync(stream);
IDictionary<string, string> bodyPartFiles = stream.BodyPartFileNames;
IList<string> newFiles = new List<string>();
foreach (var item in bodyPartFiles)
{
var newName = string.Empty;
var file = new FileInfo(item.Value);
if (item.Key.Contains("\""))
newName = Path.Combine(file.Directory.ToString(), item.Key.Substring(1, item.Key.Length - 2));
else
newName = Path.Combine(file.Directory.ToString(), item.Key);
File.Move(file.FullName, newName);
newFiles.Add(newName);
}
}
catch (Exception e)
{
}
}
}
The ASP.NET runtime waits for it. You may find this video useful.
Most examples for async assume a UI context. ASP.NET also provides a context, but it's a "request" context - one for each HTTP request. My async/await post gives an overview of this "context", and the async/await FAQ goes into much more detail.
With return type void you don't wait for an object to return.. You wait for an operation to finish. You wait for your Task to finish.
If you return void, you will be returning 204 "No Content" Response message immediately regardless of the completion status of your asynchronous operation. This is done by the help of VoidResultConverter.
Note: On RC, you will see that it returns 200 "OK" response but with
the RTM, it will return 204 "No Content" response.

Categories

Resources