|
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.
|
|
|
|
|
The reason that you return Task from an async method rather than void relates to the fact that returning void consumes exceptions that are being thrown. If you return Task, you have the ability to handle the exception gracefully. As for your code sample, you don't need to add an await on a Task.Run to get the ContinueWith to happen. In fact, you should remove that await altogether - if you're manually running up a Task here, you don't need async/await constructs.
|
|
|
|
|
If a controller method is returning Task or Task<t>, then my front end method would need to be async, correct?
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
The async -ness of your front-end methods is unrelated to the async -ness of your controller methods. You can have an async front-end method calling a non-async controller method, or a non-async front-end method calling an async controller method.
The front-end code is making a network request. It doesn't know or care how that request was fulfilled. The server could be using a synchronous method, an async method, or waiting for a carrier-pigeon. The front-end just needs to wait for the response.
Having said that, your front-end method should always be async if possible. It's making a network request, so you don't want to block a thread waiting for that to complete.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Richard Deeming wrote: The async-ness of your front-end methods is unrelated to the async-ness of your controller methods. You can have an async front-end method calling a non-async controller method, or a non-async front-end method calling an async controller method.
OK, so when I try this:
private async void GetSomeData()
{
var myData = await GiveSomeData();
}
private int GiveSomeData()
{
return 10;
}
I get a compiler error because GiveSomeData doesn't return a Task. How then do you call asynchronously call a method like GiveSOmeData?
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
Within the same process, you can only use await when you're calling something that returns an awaitable object. That typically means either a Task or a ValueTask .
Your question was about calling a Web API from some front-end code. Those are two completely separate processes, which communicate via a network request. They know nothing about each other. They could be written in completely different languages.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I see. Thank you
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
async is not really about multi-threading; it's about not blocking the current thread waiting for an external resource.
In your example, there are two external resources - the API, and the database.
The front-end call needs to use an async call to the API, since it's a network request which could take a while to run. You don't want your UI thread blocked whilst it's waiting for that request to complete.
The controller methods need to use async calls to the database, since that's potentially another network call, plus disk access, plus the time it takes the DBMS to parse and execute the query.
Think of it like a car trip. In the non-async world, your kids are in the back seat constantly asking "Are we there yet?" over and over again until you arrive. In the async world, your kids sit quietly watching a film on their phone, and wait for you to tell them once you've arrived. One of those options is extremely irritating.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thank you for clarifying.
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|