Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have a question of understanding. Which is the better option in terms of safety and performance?
private ConcurrentDictionary<string, ProfitTarget> chartTraderTP;
if (chartTraderTP.ContainsKey(orderId))
{
//Store values for later use in Mouse Events
chartTraderTP[orderId].OrderLabelRectText = rectTextOrderLabelTP;
//We can draw the Rectangle based on the TextLayout used above
if (!chartTraderTP[orderId].IsMovingOrder
&& (ChartTraderDisplayStyle == ChartTraderDisplayStyle.Own
|| ChartTraderDisplayStyle == ChartTraderDisplayStyle.Both))
{
RenderTarget.FillRectangle(rectTextOrderLabelTP, tpAreaBrushDx);
RenderTarget.DrawRectangle(rectTextOrderLabelTP, tpOutlineBrushDx,
LabelOutlineWidthTP);
RenderTarget.DrawTextLayout(vectText, tpTextLayout, tpTextBrushDx,
SharpDX.Direct2D1.DrawTextOptions.NoSnap);
}
}
or
private ConcurrentDictionary<string, ProfitTarget> chartTraderTP;
//Store values for later use in Mouse Events
if (chartTraderTP.ContainsKey(orderId))
{
chartTraderTP[orderId].OrderLabelRectText = rectTextOrderLabelTP;
}
//We can draw the Rectangle based on the TextLayout used above
if (chartTraderTP.ContainsKey(orderId) && !chartTraderTP[orderId].IsMovingOrder
&& (ChartTraderDisplayStyle == ChartTraderDisplayStyle.Own
|| ChartTraderDisplayStyle == ChartTraderDisplayStyle.Both))
{
RenderTarget.FillRectangle(rectTextOrderLabelTP, tpAreaBrushDx);
RenderTarget.DrawRectangle(rectTextOrderLabelTP, tpOutlineBrushDx,
LabelOutlineWidthTP);
RenderTarget.DrawTextLayout(vectText, tpTextLayout, tpTextBrushDx,
SharpDX.Direct2D1.DrawTextOptions.NoSnap);
}
The code is executed very often, and I would like to make the access as fast as possible but still threadsafe.
Neither are safe, as you're performing multiple operations while assuming the collection isn't changing between operations, which is not a safe assumption.
Since you want to use a number of different operations and need entire section to be logically atomic, just use a regular Dictionary and lock around the access to it.
lock (chartTraderTP)
{
//Store values for later use in Mouse Events
chartTraderTP[orderId].OrderLabelRectText = rectTextOrderLabelTP;
//We can draw the Rectangle based on the TextLayout used above
if (!chartTraderTP[orderId].IsMovingOrder && (ChartTraderDisplayStyle == ChartTraderDisplayStyle.Own || ChartTraderDisplayStyle == ChartTraderDisplayStyle.Both))
{
RenderTarget.FillRectangle(rectTextOrderLabelTP, tpAreaBrushDx);
RenderTarget.DrawRectangle(rectTextOrderLabelTP, tpOutlineBrushDx, LabelOutlineWidthTP);
RenderTarget.DrawTextLayout(vectText, tpTextLayout, tpTextBrushDx, SharpDX.Direct2D1.DrawTextOptions.NoSnap);
}
}
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 months ago.
Improve this question
menu2:
WriteLine("New category");
WriteLine("***************************");
WriteLine();
Write("Name: ");
string categoryName = ReadLine();
WriteLine("Is this correct? (Y)es (N)o");
Category category = new Category(categoryName);
do
{
userInput = ReadKey(true);
invalidSelection = !(userInput.Key == ConsoleKey.Y ||
userInput.Key == ConsoleKey.N);
}
while (invalidSelection);
var categoryExist = categoryList.Any(x => x.CategoryName == categoryName);
switch (userInput.Key)
{
case ConsoleKey.Y:
{
if (!categoryExist)
{
categoryList.Add(category);
Clear();
WriteLine("Category created!");
Thread.Sleep(2000);
}
else
{
Clear();
WriteLine("Category already exist");
Thread.Sleep(2000);
Clear();
}
break;
}
case ConsoleKey.N:
Clear();
goto menu2;
}
break;
I'm kinda new to programming and I've realized that people reaaalllyy don't like "goto"-methods. What else can i use? For example, in the code, the user inputs a category, and is then asked wether he/she typed in the category name correctly if YES then we add it if NO then u jump back to Name and have to type it in one more time. How could I do this without having to use go-to method?
You already use the same thing in your code - a do-while loop will do nicely.
It also helps to separate your code into logical blocks "hidden" in methods. That can help the readability of code like this, where you have distinct menus - instead of having a long block of code with multiple gotos, you can keep each level of the menu as its own method, and each call can be surrounded by a loop (or the method itself, depending on your preference).
Methods also give you the option to use return, which in many similar cases serves as a good replacement for goto-using code.
As you get deeper into understanding C#, new options for simplification and/or abstraction open up. For example, you can replace multiple occurrences of the same (logical) loop with functions or classes/interfaces. No rush, though :)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I am working on a codebase a student with questionable knowledge made, here I am just confused if there is any reasonable intend there or if its just unnecessary... I personally would just use the ShowNewButton field and trash the _showNewBtn, please provide an opinion.
private _showNewBtn;
public bool ShowNewButton
{
get => _showNewBtn;
set
{
bbNew.Visibility = value == false ? BarItemVisibility.Never : BarItemVisibility.Always;
_showNewBtn = value;
}
}
I see no reason (in the sample you provided) for the _showNewBtn.
You now have 2 markers which contain the visibility state of the button. At some point, this will cause problems if you aren't carefull.
Either remove the _showNewBtn completely:
public bool ShowNewButton
{
get => bbNew.Visibility == BarItemVisibility.Always;
set
{
bbNew.Visibility = value == false ? BarItemVisibility.Never : BarItemVisibility.Always;
}
}
Or justify the existance of _showNewBtn which makes my remark null and void.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have a "Panel" model that has multiple "Panel Pages". I would like to get a list of all panels, and fill each panel with its respective "Panel Pages".
Here is my code currently (that works):
public IEnumerable<DynamicCustomPanel> GetCustomPanels()
{
var customPanels = _customPanelService.GetDynamicCustomPanels();
var dynamicCustomPanels = customPanels.ToList();
foreach (var customPanel in dynamicCustomPanels.ToList())
{
var customPanelPages = _customPanelPageService.GetCustomPanelPages(customPanel.PanelGUID.ToString());
customPanel.CustomPanelPages = customPanelPages;
}
return dynamicCustomPanels;
}
How do I do this in an minimal amount of lines?
This should work:
public IEnumerable<DynamicCustomPanel> GetCustomPanels()
{
return _customPanelService.GetDynamicCustomPanels().Select(p => {
p.CustomPanelPages = _customPanelPageService.GetCustomPanelPages(p.PanelGUID.ToString());
return p;
});
}
That's technically 3 statements (two returns and an assignment) and one block, though it's kind of an abuse of the Select() method. I might write it like this instead:
public IEnumerable<DynamicCustomPanel> GetCustomPanels()
{
foreach(var p in _customPanelService.GetDynamicCustomPanels())
{
p.CustomPanelPages = _customPanelPageService.GetCustomPanelPages(p.PanelGUID.ToString());
yield return p;
}
}
Which is... also 3 statements (counting foreach) and one block, just spaced different to use one more line of text.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Can anyone assist on below WPF GUI how to convert to Linq due to low performance:
foreach (Grid b in main_grid.Children)
{
foreach (Control s in b.Children)
{
if (s.GetType() == typeof(Button))
{
if (s.Tag.ToString() == message)
{
if (status == "OIRS_INUSE")
{
s.Background = Brushes.Orange;
}
else
{
s.Background = defaultBackground;
}
}
}
}
}
First, you are asking the wrong question. Linq doesn't help.
One way to speed up this loop is to reduce the workload of its bottleneck:
foreach (Grid b in main_grid.Children)
{
foreach (Control s in b.Children)
{
if (s.SomeEnumValue == SomeEnum.Value)
{
s.Background = Brushes.Orange;
}
else
{
s.Background = defaultBackground;
}
}
}
First comparison if (s.GetType() == typeof(Button)) is costly:
for 100 million calls:
typeof(Test): 2756ms
TestType (field): 1175ms
test.GetType(): 3734ms
you'll have more than 5 times slower than a simple field comparison.
Second comparison if (s.Tag.ToString() == message) and third comparison status == "OIRS_INUSE" are costly
Moreover, the second comparison contains a ToString method which has its own cost.
So get rid of all these expensive comparisons and replace them with a simple field comparison such as an enum which is cheap.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am going Round-Robin Algorithm. I am doing in that everything must be created dynamically and Randomly. When I want to go second time to check if I have and value the is more than 0 in the checking point it says that "The given key was not present in the dictionary". How can I Fix this problem.
private int GetNextNodeToProcesssRandom()
{
int NextNodeIndex = -1;
if (NextNodeToProcess >= this.waytosave.Count)
{
NextNodeToProcess = 0;
}
for (int i = NextNodeToProcess; i < this.waytosave.Count; i++)
{
if (this.waytosave[i] > 0)//the problem appears here when the cod goes for the second time.
{
NextNodeIndex = i;
break;
}
}
NextNodeToProcess++;
return NextNodeIndex;
}
It is somehow unclear what is your exact goal. However if you want to loop through a Dict you can use:
foreach(KeyValuePair<TKey, TValue> entry in MyDict)
{
// do something with entry.Value or entry.Key
}
Now if you want to add a check in your program you can try:
if (MyDict.ContainsKey(this.waytosave[i]))
///continue execution...
A look here might help you