|
Richard Deeming wrote: o let the caller continue before the loop has finished, you'd need to yield control before starting the loop.
Wouldn't you want to do this all the time?
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
No, why would you? Just makes the processor waste time switching between things slowing down everything. It will not even start a new thread, just make the called code wait, instead of the caller.
An important thing to know is: Async/await is NOT concurrent programming. I will not start any new threads - it will not cause anything to be processed at the same time... only the method you call with an "await" can start work in parallel (by scheduling IO to complete on the IO completion threads, thread pool, it's own thread, or responding to events from other parts of the code potentially running on a different thread).
Sure, it can be used along with concurrency - and the way it is implemented can result in you running code concurrently that you did not expect - but that is a side effect and one of the things that makes async programming so hard.
Async on the server is not "invented to make the programmers life much easier". It is invented to get extra performance out of servers as they will waste less time context switching. It has been available for many many years (decades), but was horrible to program. Now we have async/await it is no longer horrible... just difficult. This is something you will notice as soon as you leave the safe path of demo applications.
|
|
|
|
|
Thanks for all the info. I appreciate it.
The reason I'm exploring this is because I'm working on a WPF app that calls SQL on my client's in-house server. Until now it's been a typcial synchronius, client-server model.
But now I'm going to be adding in a Xamarin Forms or .Net Maui app that allows my client to do work in the field. This means creating a web api and making calls async.
So, I'm trying to understand how to write both the back end and front end methods so that I don't hang the UI.
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
As mentioned by others - do not worry about the server side being async. The web host will simply spin up more threads to handle the calls concurrently - and the client software will not be able to detect if you use async or not on the server.
Sure there is a limit to how many threads you can have running - but most likely the SQL server will give up before your web server. If not, then it is some serious heavy processing you are running - and either you should let someone more experienced deal with it or just run more servers. Typically you would run two servers anyway if high availability is required.
Just to be clear: You do not have to start threads yourself for the web server to run requests concurrently. The web server will do that for you.
If you do not need to get every bit of performance out of the server, the main advantage in using async on the server side is that all modern libraries expect it - and some might no longer have sync method calls available. So if you write your code async, you will never have sync code calling async methods. Sure it can be done if needed, but you need to know what you are doing to avoid deadlocks. Async code calling sync methods is never an issue.
|
|
|
|
|
SEE AND CONTINUE DISCUSSION on the WPF Forum
I have a UI with a scrollviewer like this:
I want to scroll the viewer to the top when the ItemSource changes.
<ScrollViewer x:Name="Scroller" Grid.Row="2" Margin="0,0">
<StackPanel>
<ItemsControl x:Name="containers"
ItemsSource="{Binding Whatever, NotifyOnTargetUpdated=True}"
TargetUpdated="Containers_OnTargetUpdated">
</ItemsControl>
<StackPanel>
<ScrollViewer>
public partial class MyPage: UserControl
{
public MyPage()
{
InitializeComponent();
}
private void Containers_OnTargetUpdated(object? Sender, DataTransferEventArgs E)
{
var MyScroller = (ScrollViewer) this.FindName("Scroller");
MyScroller.ScrollToHome();
}
}
This works but it's probably not the best way to do it (ie. finding a control by name).
Can I pass the ScrollViewer "object" to the TargetUpdated callback/event ? so that I don't have to referencing it by name?
It seems clunky.
I don't know exactly what magic incantations I need to google for.
CI/CD = Continuous Impediment/Continuous Despair
modified 8-Oct-21 9:03am.
|
|
|
|
|
You could try the WPF forum.
|
|
|
|
|
(obviously, I should have seen that forum)
thanks.
CI/CD = Continuous Impediment/Continuous Despair
|
|
|
|
|
The sender parameter should be the ItemsControl , in which case you just need to walk up the visual tree to find the ScrollViewer .
private void Containers_OnTargetUpdated(object? sender, DataTransferEventArgs e)
{
var current = sender as DependencyObject;
var scroller = current as ScrollViewer;
while (scroller == null && current != null)
{
current = VisualTreeHelper.GetParent(current);
scroller = current as ScrollViewer;
}
if (scroller != null)
{
scroller.ScrollToHome();
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thanks, it works.
(sorry if I did not answer before).
CI/CD = Continuous Impediment/Continuous Despair
|
|
|
|
|
Hello fellow members. Im trying to understand why my code is not catching NullReferenceException and i cant figure it out.
I'm using this code to run async function
private async Task SearchMostLessViewsAsync(DateTime dateFrom, DateTime dateTo, int amountOfNumbersSelected, int frequencyOption, int fromDrawNumber, int toDrawNumber)
{
Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{typeof(FragmentDrawsNumbersFrequency).Name}.{nameof(SearchMostLessViewsAsync)}",
new Dictionary<string, string>()
{
{nameof(dateFrom), dateFrom.ToString()},
{nameof(dateTo), dateTo.ToString()},
{nameof(amountOfNumbersSelected), amountOfNumbersSelected.ToString()},
{nameof(frequencyOption), frequencyOption.ToString()},
{nameof(fromDrawNumber), fromDrawNumber.ToString()},
{nameof(toDrawNumber), toDrawNumber.ToString()},
}
);
((MainActivity)Activity).DisplayLoadingMessage(true, GetString(Resource.String.Common_SearchTitle),
GetString(Resource.String.Common_SearchMessage));
var task = Task.Run(async () =>
{
var textResult = await SearchLeast(dateFrom, dateTo, amountOfNumbersSelected, frequencyOption, fromDrawNumber, toDrawNumber).ConfigureAwait(false);
if (!string.IsNullOrEmpty(textResult))
{
UpdateHistoryList(textResult);
DatabaseFunctions.SaveHistoryList(HistoryList, Settings.DrawsNumbersFrequencyHistoryListViewKey);
((MainActivity)Activity).ShowSearchResults(textResult);
}
}, ApplicationState.GetCancellationToken());
try
{
await task.ConfigureAwait(false);
}
catch (TaskCanceledException tce)
{
Console.WriteLine($"{nameof(TaskCanceledException)} thrown with message: {tce.Message}");
}
catch (System.ObjectDisposedException ode)
{
Console.WriteLine($"{nameof(System.ObjectDisposedException)} thrown with message: {ode.Message}");
}
catch (System.OperationCanceledException e)
{
Console.WriteLine($"{nameof(System.OperationCanceledException)} thrown with message: {e.Message}");
}
catch (NullReferenceException nre)
{
Console.WriteLine($"{nameof(NullReferenceException)} thrown with message: {nre.Message}");
}
finally
{
ApplicationState.DisposeCancellationTokenSource();
((MainActivity)Activity).DisplayLoadingMessage(false);
}
((MainActivity)Activity).DisplayLoadingMessage(false);
}
But sometimes i get this exception
FragmentDrawsNumbersFrequency.SearchMostLessViewsAsync (System.DateTime dateFrom, System.DateTime dateTo, System.Int32 amountOfNumbersSelected, System.Int32 frequencyOption, System.Int32 fromDrawNumber, System.Int32 toDrawNumber)
FragmentDrawsNumbersFrequency.ShowMostLessViews ()
FragmentDrawsNumbersFrequency.<OnCreateView>b__50_8 (System.Object sender, System.EventArgs e)
AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state)
SyncContext+<>c__DisplayClass2_0.<Post>b__0 ()
Thread+RunnableImplementor.Run ()
IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this)
(wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.61(intptr,intptr)
I'm not sure why. Shouldn't the try catch wrap catch nullreference exceptions? Something tells me i miss something else here
modified 2-Oct-21 8:56am.
|
|
|
|
|
The exception is referring to this method: SearchMostLessViewsAsync . That's not anywhere in the code you're showing here.
|
|
|
|
|
As Pete has said, the error isn't in the code you show, nor is the method that throws the error directly called in any of that code.
Run your program in the debugger and when it fails, it will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, the debugger will stop before the error, and let you examine what is going on by stepping through the code looking at your values.
But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
modified 2-Oct-21 8:14am.
|
|
|
|
|
Richard? Are you saying I'm a complete and utter Richard?
|
|
|
|
|
No I'm saying I'm a complete and utter pillock ...
Sorry ... fixed.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
what means to be a Richard? i didnt get the joke
|
|
|
|
|
Griff called me Richard. He's edited the post to use my name now.
|
|
|
|
|
I made a mistake, and referred to Pete as Richard, is all. No joke, just a mistake on my part.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
oh i though it had a deeper meaning i didn't get
|
|
|
|
|
oh yes you are right, sorry i have used the wrong part of the code. i edit the question again.
I cant reproduce the bug in my device, it is happening in around 2% of the devices that is being used, this code is from an app that is available from google play already
|
|
|
|
|
You're making the assumption that the method that is throwing the null reference is inside your task. What's interesting is that you have failed to apply any forms of input guards to SearchMostLessViewsAsync and you're assuming you actually have values coming in. It wouldn't surprise me if the null reference you are seeing occurred in this call:
Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{typeof(FragmentDrawsNumbersFrequency).Name}.{nameof(SearchMostLessViewsAsync)}",
new Dictionary<string, string>()
{
{nameof(dateFrom), dateFrom.ToString()},
{nameof(dateTo), dateTo.ToString()},
{nameof(amountOfNumbersSelected), amountOfNumbersSelected.ToString()},
{nameof(frequencyOption), frequencyOption.ToString()},
{nameof(fromDrawNumber), fromDrawNumber.ToString()},
{nameof(toDrawNumber), toDrawNumber.ToString()},
}
);
If any of those is null, you'll get a null reference because you're calling ToString() on it. The bottom line is that you shouldn't make assumptions about where exceptions are occurring; look at the whole part of the code.
|
|
|
|
|
hello, those values cannot ever be null from the way im setting them app and also from the crash reports they are not null, they have a value, the crash comes later. some times this code doesnt crash. some times it does. even in the devices that crash it doesnt crash always.
From what i understand my biggest problem is that i dont try catch inside the task and i loose exceptions because of that. I have added a try catch inside the task and now i see that even in my device thaat never crash sometimes i get an error about ssl.
The correct way is to check all those values if they are null in the beggining of the function even if by the way are initialized always have value?
|
|
|
|
|
im Programing one Program(editor)
my question is how i can open one file txt in open with in right click and my program read the file
can you help please???
I searched for this question a lot but I could not find anything. Please help me find the answer to this question.
thanks
|
|
|
|
|
You're going to have to be more specific. "Right-click" in what?
|
|
|
|
|
|
I see a lot of tutorials and examples that define controller methods like this:
[HttpGet]
public async Task<IEnumerable<Book>> GetBooks()
{
return await _bookRepository.Get();
}
[HttpGet("{id}")]
public async Task<ActionResult<Book>> GetBooks(int id)
{
return await _bookRepository.Get(id);
}
In these examples, the method signature returns a Task so that the method is async.
But can I just do this in my front end?
private async void LoadBooks()
{
List books = null;
await Task.Run(() =>
{
books = _proxy.GetBooks()
}).ContinueWith(x =>
{
Books = new List(books);
});
}
Why make the controller methods return task and use await? Doesn't my front end code acheive that?
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
modified 29-Sep-21 17:47pm.
|
|
|
|
|