Waiting for a parse.com async task to finish in Unity3D - c#

As part of my school project I'm trying to link two tables to decrease the amount of data stored in one table so I wanted to link my "Scores" class with my "CorrectAnswers" class via the ObjectID. However since the tasks are asynchronous, by the time one task is done saving, the other task has already begun or also finished saving and so the ObjectID returns as null.
Here's the code I'm using:
public void SaveScore()
{
ParseObject SendScore = new ParseObject("Scores");
SendScore["Score"] = CheckAnswer.score;
SendScore["user"] = ParseObject.CreateWithoutData("_User", ParseUser.CurrentUser.ObjectId);
SendScore["TestMode"] = MainMenu.testmode;
SendScore["TotalQuestions"] = QuestionCreation.TotalQuestions;
SendScore["CorrectQuestions"] = CheckAnswer.CorrectQuestions;
SendScore.SaveAsync().ContinueWith(t =>
{
ScoreObjectId = SendScore.ObjectId;
});
ParseObject SendCorrectTopics = new ParseObject("CorrectAnswers");
SendCorrectTopics["Score"] = SendScore.ObjectId;
for (int i = 0; i <= 9; i++)
{
string Topic = "Topic" + (i + 1).ToString();
SendCorrectTopics[Topic] = CheckAnswer.CorrectTopics[i];
}
SendCorrectTopics.SaveAsync();
SceneManager.LoadScene(0);
}
How would I be able to make the second save hold until the first save has finished? I'm somewhat new to C# and so don't quite know all it's features yet. I've looked into "await" but unity doesn't seem to like that. Any help would be greatly appreciated!
Thanks in advance,

EDIT: Okay, after a bit more reading on Unity's coroutines, I found a much better way of checking that only relies on checking when needed:
IEnumerator CheckSave()
{
while(ScoreObjectId == null & !DoneSave))
{
print("Running");
yield return new WaitForSeconds(0.5f);
}
DoneSave = false;
SaveTotalTopics();
}
This seems like a much better way of doing it.
Well, it seems the answer was something I've already done before, even if it is a little ugly.
Using Unity's update function I created a check to make sure the ObjectID is not null and the previous save had completed, as so:
void Update () {
if (ScoreObjectId != null & DoneSave)
{
DoneSave = false;
SaveTotalTopics();
}
Thus splitting it into two saves and creating:
public void SaveScore()
{
ParseObject SendScore = new ParseObject("Scores");
SendScore["Score"] = CheckAnswer.score;
SendScore["user"] = ParseObject.CreateWithoutData("_User", ParseUser.CurrentUser.ObjectId);
SendScore["TestMode"] = MainMenu.testmode;
SendScore["TotalQuestions"] = QuestionCreation.TotalQuestions;
SendScore["CorrectQuestions"] = CheckAnswer.CorrectQuestions;
Task SendingScores = SendScore.SaveAsync().ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
DoneSave = false;
print(t.Exception);
}
else
{
DoneSave = true;
print("Setting object ID!");
ScoreObjectId = SendScore.ObjectId;
print(ScoreObjectId);
}
});
}
void SaveTotalTopics()
{
for (int i = 0; i <= 9; i++)
{
string Topic = "Topic" + (i + 1).ToString();
SendCorrectTopics[Topic] = CheckAnswer.CorrectTopics[i];
}
SendCorrectTopics["UserScore"] = ParseObject.CreateWithoutData("Scores", ScoreObjectId);
SendCorrectTopics.SaveAsync().ContinueWith(t =>
{
if(t.IsFaulted || t.IsCanceled)
{
print(t.Exception);
}
else
{
print("Saved!");
}
});
}
I'd also forgotten to use ParseObject.CreateWithoutData() so my first code snippet wouldn't have worked even if I'd found a better method...
So, although I'm not happy with the final result, at least it works and I don't think running an if statement every frame should significantly impact on my game's performance.

Why not use a bool and a while loop?
public IEnumerator SaveScore()
{
bool canContinue = false;
ParseObject SendScore = new ParseObject("Scores");
SendScore["Score"] = CheckAnswer.score;
SendScore["user"] = ParseObject.CreateWithoutData("_User", ParseUser.CurrentUser.ObjectId);
SendScore["TestMode"] = MainMenu.testmode;
SendScore["TotalQuestions"] = QuestionCreation.TotalQuestions;
SendScore["CorrectQuestions"] = CheckAnswer.CorrectQuestions;
SendScore.SaveAsync().ContinueWith(t =>
{
ScoreObjectId = SendScore.ObjectId;
//set the bool canContinue to true because the first portion of code has finished running
canContinue = true;
});
//wait while the canContinue bool is false
while(!canContinue){
yield return null;
}
//continue your parse code
ParseObject SendCorrectTopics = new ParseObject("CorrectAnswers");
SendCorrectTopics["Score"] = SendScore.ObjectId;
for (int i = 0; i <= 9; i++)
{
string Topic = "Topic" + (i + 1).ToString();
SendCorrectTopics[Topic] = CheckAnswer.CorrectTopics[i];
}
SendCorrectTopics.SaveAsync();
SceneManager.LoadScene(0);
return null;
}

Related

How to Use a Boolean to Compare Action<int>

I have a method as below
public void RequestTPCost(Action<int> callback, Action<int> enemyCallback)
{
if (OnTPSelectionNeeded == null)
{
callback?.Invoke(0);
enemyCallback?.Invoke(0);
return;
}
if (TurnSystem.Instance.IsPlayerTurn())
{
//Player turn use shooting unit is selected and target is enemy
OnTPSelectionNeeded?.Invoke(this, new TPSelectionInfo()
{
callback = callback,
enemyCallback = enemyCallback,
TPAvailable = selectedUnit.GetTacticalPoints(),
enemyTPAvailable = targetUnit.GetTacticalPoints(),
});
}
else
{
OnTPSelectionNeeded?.Invoke(this, new TPSelectionInfo()
{
callback = callback,
enemyCallback = enemyCallback,
TPAvailable = targetUnit.GetTacticalPoints(),
enemyTPAvailable = selectedUnit.GetTacticalPoints()
});
}
}
and I use it elsewhere like this
private void UnitActionSystem_OnTPSelectionNeeded(object sender, UnitActionSystem.TPSelectionInfo e)
{
maxTP = e.TPAvailable;
maxEnemyTP = e.enemyTPAvailable;
callback = e.callback;
enemyCallback = e.enemyCallback;
TPAmount = 1;
enemyTPAmount = 0;
}
public void TPConfirm()
{
callback?.Invoke(TPAmount);
UnitActionSystem.Instance.GetSelectedUnit().
SpendTacticalPoints(TPAmount);
enemyTPAmount = Random.Range(0, (maxEnemyTP + 1));
enemyCallback?.Invoke(enemyTPAmount);
UnitActionSystem.Instance.GetTargetUnit().
SpendTacticalPoints(enemyTPAmount);
}
private void NextState()
{
switch (state)
{
case State.Aiming:
state = State.Choosing;
stateTimer = 0.1f;
UnitActionSystem.Instance.RequestTPCost(ConfirmTPCost,
ConfirmEnemyTPCost);
break;
case State.Choosing:
state = State.Shooting;
float shootingStateTime = 0.1f; //Not a frame
stateTimer = shootingStateTime;
break;
case State.Shooting:
state = State.Cooloff;
float coolOffStateTime = 0.5f;
stateTimer = coolOffStateTime;
Debug.Log("Shooting");
break;
case State.Cooloff:
ActionComplete();
break;
}
}
private void ConfirmTPCost(int value)
{
Debug.Log($"TP = {value}");
NextState();
}
private void ConfirmEnemyTPCost(int value)
{
Debug.Log($"EnemyTP = {value}");
//NextState();
}
Now I want to check if ConfirmTPCost < ConfirmEnemyTPCost but am not sure how to simply do that.
I have a roundabout way using events and more UnityActionSystem functions to call the instance and work through that but it seems very clunky and prone to breaking. Is there a better way to get these values and check which is more?
var cost = 0;
var enemyCost = 0;
UnitActionSystem.Instance.RequestTPCost(i => cost = i, i => enemyCost = i);
Debug.Log($"TP = {cost}");
Debug.Log($"EnemyTP = {enemyCost}");
if (cost < enemyCost)
{
//Do your stuff here
}
As said it sounds like there is actually some asynchronous parts involved.
So you either will want to properly implement async and await patterns and wait for both values to be available.
Or alternatively you could somewhat fake that behavior using e.g. nullables and a local function ike
int? cost = null;
int? enemyCost = null;
UnitActionSystem.Instance.RequestTPCost(i =>
{
cost = i;
if(enemyCost != null)
{
Validate();
}
}, i =>
{
enemyCost = i;
if(cost != null)
{
Validate();
}
});
// Can be a local function
// otherwise pass in the two int values via parameters
void Validate()
{
Debug.Log($"TP = {cost.Value}");
Debug.Log($"EnemyTP = {enemyCost.Value}");
if (cost.Value < enemyCost.Value)
{
//Do your stuff here
}
}
Idea here: No matter which of both callbacks fires first, it is ignored and only for the second one both values are already available and the actual handler method can be invoked

Error when pulling from database to create objects after successful creation

Let me start by apologizing for the complexity of this post. hopefully I am missing something simple but in order to find out I have to make a lengthy explanation.
I'm building a staff tracking app that allows users to draw polygons on a map. The polygon is used as a zone. If the device location is inside the zone it will set them to one status such as "In" and then set them to another status like "Out" when they leave. I'm using several nugets; SQLite, TK.CustomMap, PopupPlugin, to accomplish as much of this as possible in the Shared Project. The SQLite data model is based on the structure of the remote database for the solution which also has a desktop application, web app, and many other interfaces so that structure must be maintained.
The tables involved in this operation are Zones, ZonePoints and StatusClass. When the Zone is saved the Points of the TK.Polygon are saved into the points table. The Statuses assigned to the in and out status of the Zone are assigned to the zone as is the zone name.
The process works this way - first the user clicks on a button to add the zone. This creates a new zone, saves it to the database and gets its id from the table. For now, the ZoneSys (Primary Key in the remote db) is also set to the id although when the API is ready this will be Auto Incremented in the remote db. Here is that command and the objects it references. I did not include the database method definitions given that they work on the first time through, but if anyone thinks they will help solve this riddle please let me know -
public static List<Position> ActiveZonePositions = new List<Position>();
public static int ActiveZoneID;
public static Zone ActiveZone;
public static int PointCount;
public static bool NewZoneOpen = false;
public Command<EventArgs> OpenNewZone
{
get
{
return new Command<EventArgs>(async e =>
{
NewZoneOpen = true;
PointCount = 0;
ActiveZonePositions.Clear();
Zone ZoneToAdd = new Zone
{
Contactsys = MobileUser.ContactSys,
ZoneTypeSys = 1,
OrganizationSys = MobileUser.OrganizationSys,
ZoneName = null
};
ActiveZoneID = await AddZoneToDBAsync(ZoneToAdd);
ZoneToAdd.ID = ActiveZoneID;
ZoneToAdd.ZoneSys = ActiveZoneID;
await AddZoneToDBAsync(ZoneToAdd);
ActiveZone = await App.Database.GetZoneAsync(ActiveZoneID);
});
}
}
As the user click points in the map the polygon is drawn using those positions and those positions are also used to create points which are added to a static list. Here is the MapClicked_Command -
public Command<Position> MapClickedCommand
{
get
{
return new Command<Position>(async position =>
{
if (NewZoneOpen)
{
bool isPointInPolygon = IsPointInAnyPolygon(position);
if (isPointInPolygon)
{
var action = await Application.Current.MainPage.DisplayActionSheet(
"Region Collides with Another Region",
"Cancel",
null,
"Try Again",
"Close Zone Editor");
if (action == "Close Zone Editor")
{
await RemoveZoneAsync(ActiveZoneID);
}
if (action == "Try Again")
{
return;
}
}
else if (!isPointInPolygon)
{
ActiveZonePositions.Add(position);
}
if (ActiveZonePositions.Count == 2)
{
ZonePolyLine.LineCoordinates = ActiveZonePositions;
_lines.Remove(ZonePolyLine);
_lines.Add(ZonePolyLine);
}
else if (ActiveZonePositions.Count == 3)
{
ActiveZonePositions.Add(position);
_lines.Remove(ZonePolyLine);
TKPolygon poly = new TKPolygon
{
StrokeColor = System.Drawing.Color.CornflowerBlue,
StrokeWidth = 2f,
Color = System.Drawing.Color.CornflowerBlue
};
foreach (Position pos in ActiveZonePositions)
{
poly.Coordinates.Add(pos);
}
_polygons.Add(poly);
_currentPolygon.Clear();
_currentPolygon.Add(poly);
currentPolygonRendering = true;
}
else if (ActiveZonePositions.Count > 3)
{
ActiveZonePositions.Add(position);
TKPolygon poly = new TKPolygon
{
StrokeColor = System.Drawing.Color.CornflowerBlue,
StrokeWidth = 2f,
Color = System.Drawing.Color.CornflowerBlue
};
foreach (Position pos in ActiveZonePositions)
{
poly.Coordinates.Add(pos);
}
_polygons.Remove(_polygons.Last());
_polygons.Add(poly);
_currentPolygon.Clear();
_currentPolygon.Add(poly);
}
var pin = new TKCustomMapPin
{
Position = new TK.CustomMap.Position(position.Latitude, position.Longitude),
Title = string.Format("Pin {0}, {1}", position.Latitude, position.Longitude),
IsVisible = true,
IsDraggable = true,
ShowCallout = true
};
_pins.Add(pin);
await CreatePointAsync(position);
PointCount++;
}
else if (EditZoneOpen)
{
ActiveZonePositions.Add(position);
var poly = _polygons[0];
poly.Coordinates.Clear();
foreach (Position pos in ActiveZonePositions)
{
poly.Coordinates.Add(pos);
}
_polygons.Remove(_polygons.Last());
_polygons.Add(poly);
_currentPolygon.Clear();
_currentPolygon.Add(poly);
var pin = new TKCustomMapPin
{
Position = new TK.CustomMap.Position(position.Latitude, position.Longitude),
Title = string.Format("Pin {0}, {1}", position.Latitude, position.Longitude),
IsVisible = true,
IsDraggable = true,
ShowCallout = true
};
_pins.Add(pin);
await CreatePointAsync(position);
PointCount++;
}
});
}
}
Here is the CreatePointAsyncMethod -
public async Task CreatePointAsync(TK.CustomMap.Position position)
{
var zone = await RetrieveZoneAsync(ActiveZoneID);
Model.Point PointToAdd = new Model.Point
{
ZoneSys = zone.ZoneSys,
PointName = "",
Latitude = position.Latitude,
Longitude = position.Longitude,
PointOrder = PointCount + 1
};
ActiveZonePoints.Add(PointToAdd);
}
Here is the IsPointInAnyPolygon method that checks against the list of polygons to ensure the point clicked is not inside any of them as well as its supporting methods.
private bool IsPointInAnyPolygon(Position position)
{
bool inBounds = false;
for (var i = 0; i < ZonePolygons.Count(); i++)
foreach (ZonePolygon zpoly in ZonePolygons)
{
TKPolygon tkpoly = zpoly.Zpolygon;
inBounds = IsPointInPolygon(position, tkpoly.Coordinates);
if (inBounds)
{
ActiveZoneID = zpoly.ID;
return inBounds;
}
}
return inBounds;
}
private bool IsPointInPolygon(TK.CustomMap.Position position, List<Position> coords)
{
int intersectCount = 0;
for (int j = 0; j < coords.Count() - 1; j++)
{
if (j+1 >= coords.Count())
{
if (rayCastIntersect(position, coords[j], coords[0]))
{
intersectCount++;
}
} else if (rayCastIntersect(position, coords[j], coords[j + 1]))
{
intersectCount++;
}
}
return ((intersectCount % 2) == 1); // odd = inside, even = outside;
}
private bool rayCastIntersect(TK.CustomMap.Position position, TK.CustomMap.Position vertA, TK.CustomMap.Position vertB)
{
double aY = vertA.Latitude;
double bY = vertB.Latitude;
double aX = vertA.Longitude;
double bX = vertB.Longitude;
double pY = position.Latitude;
double pX = position.Longitude;
if ((aY > pY && bY > pY) | (aY < pY && bY < pY)
| (aX < pX && bX < pX))
{
return false; // a and b can't both be above or below pt.y, and a or
// b must be east of pt.x
}
double m = (aY - bY) / (aX - bX); // Rise over run
double bee = (-aX) * m + aY; // y = mx + b
double x = (pY - bee) / m; // algebra is neat!
return x > pX;
}
Upon clicking the save button a popup opens that allows the user to give the Zone a name, define the statuses it will be assigned and the points are added to the database. There is a ZoneSys column in the Points table which allows the points to be matched to their respective zones when retrieved. This is done withe the UpdateZone command
public Command<EventArgs> UpdateZone
{
get
{
return new Command<EventArgs>(async e =>
{
Zone zone = await App.Database.GetZoneAsync(ActiveZoneID);
zone.ZoneName = ZoneParameters.ZoneName;
zone.StatusSys = ZoneParameters.InStatus.StatusSys;
zone.OutOfZoneStatusSys = ZoneParameters.OutStatus.StatusSys;
await AddZoneToDBAsync(zone);
if (MapPage.SaveZoneInfoPopupPageOpen)
{
SavePointsOnExit();
MapPage.SaveZoneInfoPopupPageOpen = false;
}
});
}
}
The UpdateZone command calls the SavePointsOnExit method
private async void SavePointsOnExit()
{
ActiveZonePoints.OrderBy(o => o.PointOrder);
for (var i = 0; i < ActiveZonePoints.Count(); i++)
{
Model.Point PointToAdd = new Model.Point();
PointToAdd = ActiveZonePoints[i];
ActivePointID = await AddPointToDBAsync(PointToAdd);
PointToAdd.ID = ActivePointID;
PointToAdd.PointSys = ActivePointID;
await AddPointToDBAsync(PointToAdd);
}
try
{
Zone zone = await RetrieveZoneAsync(ActiveZoneID);
}
catch
{
await Application.Current.MainPage.DisplayActionSheet("no zone returned", "database error", "cancel");
}
try
{
Zone zone = await RetrieveZoneAsync(ActiveZoneID);
await CreateZonedPolygonAsync(zone);
}
catch
{
await Application.Current.MainPage.DisplayActionSheet("Could not create ZonePolygon", "object error", "cancel");
}
ActiveZonePoints.Clear();
ActiveZonePositions.Clear();
NewZoneOpen = false;
ClearPins();
PointCount = 0;
PopulatePoints();
}
In addition to saving the points to the db the SaveZonePointsOnExit method also creates the ZonePolygon and adds it to an observable collection using the CreateZonedPolygonAsync method -
private async Task<ZonePolygon> CreateZonedPolygonAsync(Zone zone)
{
int StatusSys = zone.StatusSys;
var status = await App.Database.GetStatusBySysAsync(StatusSys);
int OutStatusSys = zone.OutOfZoneStatusSys;
var outStatus = await App.Database.GetStatusBySysAsync(OutStatusSys);
var points = await App.Database.GetZonePointsAsync(zone.ZoneSys);
ZonePolygon zonePolygon = new ZonePolygon
{
ID = zone.ID
};
TKPolygon poly = new TKPolygon();
foreach (Model.Point point in points)
{
poly.Coordinates.Add(new Position(point.Latitude, point.Longitude));
}
poly.Color = Color.FromHex(status.ColorCode);
poly.StrokeColor = Color.Firebrick;
poly.StrokeWidth = 5f;
_polygons.Add(poly);
ZonePolygons.Add(zonePolygon);
return zonePolygon;
}
So far all of this works to a point. I have been successful in creating the first Polygon. I don't run into a problem until I attempt to create a second Zone. When I click on the AddZone button a second time that works fine but when I click on the map to begin creating the second zone a nullreference exception occurs.
Given that the first zone is created without issue I think the problem must be arising from something that occurs when the IsPointInAnyPolygon method no longer immediately returns false because the ZonePolygons list is no longer empty. So something about the retrieving of zones from the database to check against is the problem or possibly adding coordinates when the TKPolygon is created. I don't know what has a null reference. I would think that since I am creating the Zones directly from the database that all the objects would be saved properly and their previous references wouldn't matter. I'm very stuck on this.
TL;DR there is an issue with either the CreateZonedPolygonAsync Method or the IsPointInAnyPolygon method
I figured this out. I feel rather silly because I have been stuck on this for several hours spread out over a couple of weeks. Kept coming back to it and couldn't figure it out. The issue was that in the CreateZonedPolygonAsync method I never assigned the TKPolygon created via points to the ZonePolygon object being created. So when I tried to reference it it didn't exist. All that existed was the ID. Can't believe I missed this for this long.
Of course now I'm having brand new problems but at least this is fixed.
All I had to do was add zonePolygon.Zpolygon = poly; as shown here and it works now
private async Task<ZonePolygon> CreateZonedPolygonAsync(Zone zone)
{
int StatusSys = zone.StatusSys;
var status = await App.Database.GetStatusBySysAsync(StatusSys);
int OutStatusSys = zone.OutOfZoneStatusSys;
var outStatus = await App.Database.GetStatusBySysAsync(OutStatusSys);
var points = await App.Database.GetZonePointsAsync(zone.ZoneSys);
ZonePolygon zonePolygon = new ZonePolygon
{
ID = zone.ID
};
TKPolygon poly = new TKPolygon();
foreach (Model.Point point in points)
{
poly.Coordinates.Add(new Position(point.Latitude, point.Longitude));
}
poly.Color = Color.FromHex(status.ColorCode);
poly.StrokeColor = Color.Firebrick;
poly.StrokeWidth = 5f;
zonePolygon.Zpolygon = poly;
_polygons.Add(poly);
ZonePolygons.Add(zonePolygon);
return zonePolygon;
}

Call 3 functions at the same time. Should Parallel.For be used?

Problem:
I'm currently calling 3 functions inside my code, which are executed behind each other which would take some time to finish. So I was wondering if there is a way to call them at the same time, for example using a Parallel.For loop.
In case I could use a Parallel.For loop, how would I manage to do this? Would this be the right way to use it?
Parallel.For(0, 1, i =>
{
bool check1 = function1(address);
bool check2 = function2(address);
bool check3 = function3(address);
});
My current code:
private void check()
{
for (int i = 0; i < dataGridView1.RowCount; i++)
{
string address = dataGridView1.Rows[i].Cells[0].Value.ToString();
try
{
if (address.Length < 6)
{
// Those 3 functions are currently called behind each other
// Could those be called inside a Parallel.For loop at the same time?
bool check1 = function1(address);
bool check2 = function2(address);
bool check3 = function3(address);
}
else
{
dataGridView1.Rows[i].Cells[2].Value = "Error";
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
As a quick estimation (are you going to get reasonable gain) you can try Parallel Linq (PLinq).
bool[] results = new Func<string, bool>[] {function1, function2, function3}
.AsParallel()
.AsOrdered() // <- to guarantee function / outcome correspondence
.Select(f => f(address))
.ToArray();
bool check1 = results[0];
bool check2 = results[1];
bool check3 = results[2];

C# tail recursive call vs iteration (loop)

I'm developing a poker app i almost have it done and im looking for improvements and 1 of the things i wonder about is should i change my main looping method method ? Currently it's looping by using tail recursive call. However friend of mine suggested me to switch it to a iteration since it's using a while loop and loop's don't require stack space. Here's my code as it is now.
private async Task Turns()
{
_turns = ReturnTurns();
GC.KeepAlive(Updates);
if (!Player.FoldTurn && Player.Chips > 0)
{
if (Player.Turn)
{
SetPlayerStuff(true);
Call -= Player.PreviousCall;
_up = int.MaxValue;
_turnCount++;
Bot1.Turn = true;
_restart = true;
}
}
if (!Player.Turn)
{
await Flip(0);
}
if (Player.FoldTurn || !Player.Turn || Player.Chips <= 0)
{
Call = TempCall;
if (StatusLabels[Player.EnumCasted].Contains(RepetitiveVariables.Fold))
{
Bot1.Turn = true;
}
SetPlayerStuff(false);
Bot1 = (Bot)await RotateTurns(Bot1, Bot1.EnumCasted);
Bot2 = (Bot)await RotateTurns(Bot2, Bot2.EnumCasted);
Bot3 = (Bot)await RotateTurns(Bot3, Bot3.EnumCasted);
Bot4 = (Bot)await RotateTurns(Bot4, Bot4.EnumCasted);
Bot5 = (Bot)await RotateTurns(Bot5, Bot5.EnumCasted);
_restart = false;
}
if (!_restart)
{
await Turns();
}
}
That's how i think it should look's like with a loop:
private async Task Turns()
{
while (true)
{
_turns = ReturnTurns();
GC.KeepAlive(Updates);
if (!Player.FoldTurn && Player.Chips > 0)
{
if (Player.Turn)
{
SetPlayerStuff(true);
Call -= Player.PreviousCall;
_up = int.MaxValue;
_turnCount++;
Bot1.Turn = true;
_restart = true;
}
}
if (!Player.Turn)
{
await Flip(0);
}
if (Player.FoldTurn || !Player.Turn || Player.Chips <= 0)
{
Call = TempCall;
if (StatusLabels[Player.EnumCasted].Contains(RepetitiveVariables.Fold))
{
Bot1.Turn = true;
}
SetPlayerStuff(false);
Bot1 = (Bot) await RotateTurns(Bot1, Bot1.EnumCasted);
Bot2 = (Bot) await RotateTurns(Bot2, Bot2.EnumCasted);
Bot3 = (Bot) await RotateTurns(Bot3, Bot3.EnumCasted);
Bot4 = (Bot) await RotateTurns(Bot4, Bot4.EnumCasted);
Bot5 = (Bot) await RotateTurns(Bot5, Bot5.EnumCasted);
_restart = false;
}
if (!_restart)
{
continue;
}
break;
}
}
Generally, the JIT is not able to replace recursion with a loop. This is a fairly esoteric optimization scenario.
Here, this does not even come into play because an async method uses very different call mechanisms internally.
This code will consume "stack space" proportional to the recursion depth. (It's not necessarily stack space with async methods. Could be heap space in the form of a linked list.)
From a code quality standpoint I find the loop vastly preferable because recursion is not what most people are used to. Here, there really is no algorithmic need for recursion. Seems like the wrong tool for the job. I think you have used recursion as a replacement for "goto" here because all this does is jump back to the beginning of the method.
You can make the jump condition a little cleaner:
if (!_restart) break;

Add Multiple record using Linq-to-SQL

I want to add Multiple rows into Table using Linq to SQL
public static FeedbackDatabaseDataContext context = new FeedbackDatabaseDataContext();
public static bool Insert_Question_Answer(List<QuestionClass.Tabelfields> AllList)
{
Feedback f = new Feedback();
List<Feedback> fadd = new List<Feedback>();
for (int i = 0; i < AllList.Count; i++)
{
f.Email = AllList[i].Email;
f.QuestionID = AllList[i].QuestionID;
f.Answer = AllList[i].SelectedOption;
fadd.Add(f);
}
context.Feedbacks.InsertAllOnSubmit(fadd);
context.SubmitChanges();
return true;
}
When I add records into list object i.e. fadd the record is overwrites with last value of AllList
I'm late to the party, but I thought you might want to know that the for-loop is unnecessary. Better use foreach (you don't need the index).
It gets even more interesting when you use LINQ (renamed method for clarity):
public static void InsertFeedbacks(IEnumerable<QuestionClass.Tabelfields> allList)
{
var fadd = from field in allList
select new Feedback
{
Email = field.Email,
QuestionID = field.QuestionID,
Answer = field.SelectedOption
};
context.Feedbacks.InsertAllOnSubmit(fadd);
context.SubmitChanges();
}
By the way, you shouldn't keep one data context that you access all the time; it's better to create one locally, inside a using statement, that will properly handle the database disconnection.
You should create object of Feedback in the scope of for loop, so change your method to :
public static bool Insert_Question_Answer(List<QuestionClass.Tabelfields> AllList)
{
List<Feedback> fadd = new List<Feedback>();
for (int i = 0; i < AllList.Count; i++)
{
Feedback f = new Feedback();
f.Email = AllList[i].Email;
f.QuestionID = AllList[i].QuestionID;
f.Answer = AllList[i].SelectedOption;
fadd.Add(f);
}
context.Feedbacks.InsertAllOnSubmit(fadd);
context.SubmitChanges();
return true;
}

Categories