Blazor field gets null - c#

I have this code in blazor:
It's just a simple method to update the div each second:
<div style="font-size:50px">#dailyCases.ToString("0,0.00")</div>
#code
{
private double dailyCases;
private bool needsUpdate = false;
private CovidDataManager covidManager;
protected async override Task OnInitializedAsync()
{
Console.WriteLine("init");
dailyCases = await updateData();
await StartCounter();
}
private Task StartCounter()
{
var timer = new System.Timers.Timer(1000);
timer.Elapsed += async (sender, e) =>
{
dailyCases = await update();
await InvokeAsync(StateHasChanged);
};
timer.Start();
return Task.CompletedTask;
}
private async Task<double> updateData()
{
var httpResponse = await covidRepository.GetYesterdayData("FRANCE");
var covidDailyInfoDTO = mapper.Map<Covid19Portal.Shared.DTO.CovidDailyInfoDTO>(httpResponse.Response);
var covidManager = new Covid19Portal.Shared.CovidDataManager(covidDailyInfoDTO);
return await Task.FromResult(covidManager.SickUpToNow);
}
private async Task<double> update()
{
return await Task.FromResult(covidManager.SickUpToNow);
//return await Task.FromResult(covidManager.SickUpToNow);
}
}
I get and error that covidManager is null after update gets called.
Any idea why?

Related

List.Add not added perfectly with Parallel and async

I have a Blazor WASM application that needs to call an API every second without blocking the UI. This codes demonstrates how I tried to do that:
List<int> testList = new();
testList.Add(1);
testList.Add(2);
testList.Add(3);
testList.Add(4);
List<int> emptyTestlist = new();
CancellationTokenSource cts;
Test();
void Test()
{
Parallel.Invoke(async () =>
{
do
{
Console.WriteLine("Start");
await Task.Delay(1000);
await Test2();
Console.WriteLine("END");
} while (true);
});
}
Console.ReadLine();
async ValueTask Test2()
{
emptyTestlist.Clear();
cts = new();
await Parallel.ForEachAsync(testList, cts.Token, async (test, token) =>
{
await Test4(test);
});
foreach (var test in emptyTestlist)
{
await Test3(test);
}
}
async Task Test4(int i)
{
await Task.Delay(300);
//Console.WriteLine("if I Add this console.WriteLine It's added perfectly");
emptyTestlist.Add(i);
Console.WriteLine($"from TEST4: {i}");
}
async Task Test3(int i)
{
Console.WriteLine($"TEST3 {i}.");
await Task.Delay(1000);
Console.WriteLine($"TEST3 {i}, after 1sec");
}
If I comment the line Console.WriteLine("if I Add this console.WriteLine It's added perfectly");, it's not adding perfectly. (emptyTestlist.Count is not always 4). But if I add Console.WriteLine before emptyTestlist.Add(i) it works correctly (emptyTestlist.Count is always 4).
I don't know how to solve it. What's the problem?
The easiest way to poll an API is to use a timer:
#code {
private List<Customer> custs=new List<Customer>();
private System.Threading.Timer timer;
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
custs = await Http.GetFromJsonAsync<List<Customer>>(url);
timer = new System.Threading.Timer(async _ =>
{
custs = await Http.GetFromJsonAsync<List<Customer>>("/api/customers");
InvokeAsync(StateHasChanged);
}, null, 1000, 1000);
}
In this case InvokeAsync(StateHasChanged); is needed because the state was modified from a timer thread and Blazor has no idea the data changed.
If we wanted to add the results to a list though, we'd either have to use a lock or a thread-safe collection, like a ConcurrentQueue.
#code {
private ConcurrentQueue<Customer> custs=new ConcurrentQueue<Customer>();
private System.Threading.Timer timer;
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
custs = await Http.GetFromJsonAsync<List<Customer>>(url);
timer = new System.Threading.Timer(async _ =>
{
var results = await Http.GetFromJsonAsync<List<Customer>>("/api/customers");
foreach(var c in results)
{
custs.Enqueue(c);
}
InvokeAsync(StateHasChanged);
}, null, 1000, 1000);
}
Polling an API every second just in case there's any new data isn't very efficient though. It would be better to have the API notify clients of any new data using eg SignalR or Push Notifications
Borrowing from the documentation example this would be enough to receive messages from the server:
#code {
private HubConnection hubConnection;
private List<string> messages = new List<string>();
private string userInput;
private string messageInput;
protected override async Task OnInitializedAsync()
{
hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/chathub"))
.Build();
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
var encodedMsg = $"{user}: {message}";
messages.Add(encodedMsg);
StateHasChanged();
});
await hubConnection.StartAsync();
}

Unity crashes on async programming with Firebase database

When I try to do this it crashes:
I want to get the user data async, if I don't use async task it returns null
public class Database : MonoBehaviour
{
private DatabaseReference m_database;
private const string DATA_URL = "hidden";
public static Database singleton;
void Awake ()
{
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl(DATA_URL);
m_database = FirebaseDatabase.DefaultInstance.RootReference;
DontDestroyOnLoad(this);
singleton = this;
}
void Start ()
{
User user = new User();
user = GetUserAsync("213asdasd").Result;
Debug.Log(user.email);
}
public void RegisterNewUser (User user)
{
string jsonData = JsonUtility.ToJson(user);
m_database.Child("Users").Child(user.id).SetRawJsonValueAsync(jsonData);
m_database.Child("Users").Child(user.id).Child("id").SetValueAsync(user.id);
m_database.Child("Users").Child(user.id).Child("email").SetValueAsync(user.email);
}
public async Task<User> GetUserAsync (string id)
{
User user = new User();
await FirebaseDatabase.DefaultInstance.GetReference("Users").Child(id)
.GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
// Handle the error...
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
string rawUserData = snapshot.GetRawJsonValue();
Debug.Log(rawUserData);
user = JsonUtility.FromJson<User>(rawUserData);
}
});
return user;
}
}
Mixing async-await and blocking calls can cause problems.
Reference Async/Await - Best Practices in Asynchronous Programming
Use an async event handler if the code is unable to be refactored to be async all the way
void Start () {
started += onStarted;
started(this, EventArgs.Empty);
}
event EventHandler started = delegate { }
private async void onStarted(object sender, EventArgs args) {
started -= onStarted;
User user = await GetUserAsync("213asdasd");
Debug.Log(user.email);
}
Also code should follow async all the way pattern
public async Task<User> GetUserAsync (string id) {
User user = new User();
try {
DataSnapshot snapshot = await FirebaseDatabase.DefaultInstance
.GetReference("Users").Child(id).GetValueAsync();
string rawUserData = snapshot.GetRawJsonValue();
Debug.Log(rawUserData);
user = JsonUtility.FromJson<User>(rawUserData);
} catch(Exception ex) {
// Handle the error...
}
return user;
}

C# Pausing Async Task works in one method, but not another

I have a class called PauseOrCancelToken, created by another class, PauseOrCancelTokenSource. PauseOrCancelToken basically encapsulates both a CancellationToken and PauseToken implemented from this MSDN blog post: https://blogs.msdn.microsoft.com/pfxteam/2013/01/13/cooperatively-pausing-async-methods/
I have tested it, and in a simple example use case (MethodA in the code I am about to post), it works as intended.
However, when I test it with non-trivial code that I intend to use in production (MethodB/ProxyTester.Start()), it is not pausing the async task.
public partial class PauseCancelForm : Form
{
private PauseOrCancelTokenSource pcts = new PauseOrCancelTokenSource();
public PauseCancelForm()
{
InitializeComponent();
}
private void StartButton_Click(object sender, EventArgs e)
{
Task.Run(() =>
{
MethodA(pcts.Token).Wait();
});
}
private async Task MethodA(PauseOrCancelToken pct)
{
//Pauses as intended when the pause button is clicked.
for (int i = 0; i < 10000; i++)
{
Console.WriteLine(i);
await Task.Delay(1000);
await pct.PauseOrCancelIfRequested();
}
}
private async Task MethodB(PauseOrCancelToken pct)
{
//Doesn't pause.
var proxies = new List<Proxy>();
var judges = new List<ProxyJudge>();
for (int i = 0; i < 10000; i++)
{
proxies.Add(new Proxy("127.0.0." + RandomUtility.GetRandomInt(1, 100), 8888));
}
judges.Add(new ProxyJudge("http://azenv.net"));
await ProxyTester.Start(proxies, judges, pct);
}
private void PauseButton_Click(object sender, EventArgs e)
{
pcts.Pause();
}
private void StopButton_Click(object sender, EventArgs e)
{
pcts.Cancel();
}
private void ResumeButton_Click(object sender, EventArgs e)
{
pcts.Resume();
}
}
public class PauseOrCancelTokenSource
{
private PauseTokenSource pts = new PauseTokenSource();
private CancellationTokenSource cts = new CancellationTokenSource();
public PauseOrCancelToken Token { get { return new PauseOrCancelToken(pts, cts); } }
public void Pause()
{
pts.IsPaused = true;
}
public void Resume()
{
pts.IsPaused = false;
}
public void Cancel()
{
cts.Cancel();
}
}
public class PauseOrCancelToken
{
private PauseToken pt;
private CancellationToken ct;
public PauseOrCancelToken(PauseTokenSource pts, CancellationTokenSource cts)
{
this.pt = pts.Token;
this.ct = cts.Token;
}
public async Task PauseIfRequested()
{
await pt.WaitWhilePausedAsync();
}
public void CancelIfRequested()
{
ct.ThrowIfCancellationRequested();
}
public async Task PauseOrCancelIfRequested()
{
await PauseIfRequested();
CancelIfRequested();
}
}
public class ProxyTester
{
public async static Task Start(List<Proxy> proxies, List<ProxyJudge> judges, PauseOrCancelToken pct, List<ProxyTest> tests = null)
{
if (tests == null)
{
tests = new List<ProxyTest>();
}
//Get external IP to check if proxy is anonymous.
var publicIp = await WebUtility.GetPublicIP();
//Validate proxy judges.
var tasks = new List<Task>();
foreach (var judge in judges)
{
tasks.Add(Task.Run(async () => {
judge.IsValid = await judge.TestValidityAsync();
await pct.PauseOrCancelIfRequested();
}));
}
await Task.WhenAll(tasks);
var validJudges = from judge in judges
where judge.IsValid
select judge;
if (validJudges.Count() == 0)
{
throw new Exception("No valid judges loaded.");
}
//Validate proxy tests.
tasks.Clear();
foreach (var test in tests)
{
tasks.Add(Task.Run(async () => {
test.IsValid = await test.TestValidityAsync();
await pct.PauseOrCancelIfRequested();
}));
}
await Task.WhenAll(tasks);
var validTests = from test in tests
where test.IsValid
select test;
var count = 0;
//Test proxies with a random, valid proxy judge. If valid, test with all valid proxy tests.
tasks.Clear();
foreach (var proxy in proxies)
{
tasks.Add(Task.Run(async () =>
{
proxy.IsValid = await proxy.TestValidityAsync(validJudges.ElementAt(RandomUtility.GetRandomInt(0, validJudges.Count())));
count++;
Console.WriteLine(count);
await pct.PauseOrCancelIfRequested();
if (proxy.IsValid)
{
proxy.TestedSites.AddRange(validTests);
var childTasks = new List<Task>();
foreach (var test in validTests)
{
childTasks.Add(Task.Run(async () =>
{
proxy.TestedSites.ElementAt(proxy.TestedSites.IndexOf(test)).IsValid = await proxy.TestValidityAsync(test);
await pct.PauseOrCancelIfRequested();
}));
}
await Task.WhenAll(childTasks);
}
}));
}
await Task.WhenAll(tasks);
}
}
In general, code in ProxyTester.Start uses pause token this way:
foreach (var judge in judges)
{
tasks.Add(Task.Run(async () => {
judge.IsValid = await judge.TestValidityAsync();
await pct.PauseOrCancelIfRequested();
}));
}
This runs judges.Length number of tasks. What happens when you pause token? Well, nothing useful actually. All tasks continue to run, and all of them will complete their useful work (await judge.TestValidityAsync()). Then, when all useful work is done, and they should just complete - they will pause on await pct.PauseOrCancelIfRequested(). I doubt that is the result you desire. Changing the order won't help much.
Compare that to "working" example:
for (int i = 0; i < 10000; i++)
{
Console.WriteLine(i);
await Task.Delay(1000);
await pct.PauseOrCancelIfRequested();
}
Here execution is sequential (and not parallel like above) and you check pause token every iteration, so it works as expected.
If you want to be able to pause in your real world scenario - don't start all those tasks at once, run them in batches (with SemaphoreSlim or similar technique), and check pause token after each batch.

Refactor to remove Taks.Run from my code

I just wrote the following code
public void Save()
{
while (this.IsAsyncInProcess)
Thread.Sleep(100);
this.customer.OrderCount = this.orders.Count();
this.customer.OrderTotal = this.orders.Sum(o => x.Total);
this.customerRepo.Save();
}
public async Task LoadAsync()
{
this.IsAsyncInProcess = true;
this.customer = await this.customerRepo.GetCustomerAsync(...);
this.orders = await this.customerRepo.GetOrdersAsync(...);
this.IsAsyncInProcess = false;
}
Now I had a classical deadlock because, after this.orders completed, it would wait for the gui thread to resume in order to set this.IsAsyncInProcess to false. However, the gui thread was busy inside Save()
Now I refactored LoadAsync to
public async Task LoadAsync()
{
await Task.Run(async () =>
{
this.IsAsyncInProcess = true;
this.customer = await this.customerRepo.GetCustomerAsync(...);
this.orders = await this.customerRepo.GetOrdersAsync(...);
this.IsAsyncInProcess = false;
});
}
I can't just refactor Save to SaveAsync for compability reasons.
Is there a better way to achive this, without using Task.Run?
You can use async locking. If you can't change the signiture of Save then you can just proxy to an async local function.
static SemaphoreSlim sem = new SemaphoreSlim(1,1);
public void Save()
{
SaveAsync();
public async Task SaveAsync()
{
await sem.WaitAsync();
try{
this.customer.OrderCount = this.orders.Count();
this.customer.OrderTotal = this.orders.Sum(o => x.Total);
this.customerRepo.Save();
}finally{
sem.Release();
}
}
}
public async Task LoadAsync()
{
await sem.WaitAsync();
try{
this.customer = await this.customerRepo.GetCustomerAsync(...);
this.orders = await this.customerRepo.GetOrdersAsync(...);
}finally{
sem.Release();
}
}
or even better create your own async lock
static SemaphoreSlim sem = new SemaphoreSlim(1,1);
public static async Task<IDisposable> LockAsync(){
await sem.WaitAsync();
return Disposable.Create(()=>sem.Release());
}
public void Save()
{
SaveAsync();
public async Task SaveAsync()
{
using(await LockAsync()){
this.customer.OrderCount = this.orders.Count();
this.customer.OrderTotal = this.orders.Sum(o => x.Total);
this.customerRepo.Save();
}
}
}
public async Task LoadAsync()
{
using(await LockAsync()){
this.customer = await this.customerRepo.GetCustomerAsync(...);
this.orders = await this.customerRepo.GetOrdersAsync(...);
}
}

C# - How to run multi await in one method?

I don't know how to run multi await methods in single method. For example my code as below:
public static async Task<bool> Authenticate()
{
bool authen = false;
string message = String.Empty;
try
{
session = await FacebookSessionClient.LoginAsync("user_about_me,read_stream");
fbAccessToken = session.AccessToken;
fbFacbookID = session.FacebookId;
await saveProfile(fbFacebookID); //error here,my app is closed at here
authen = true;
}
catch (InvalidOperationException e)
{
authen = false;
}
return authen;
}
And I have method save profile
public async static void saveProfile(string fbFacbookID)
{
string response = string.Empty;
if (!string.IsNullOrEmpty(fbFacbookID))
{
response=await StaticClass.getJsonStream(string.Format("http://graph.facebook.com/{0}", fbFacbookID));
JObject _object = JObject.Parse(response);
SaveValueSetting("usernameFB",(string)_object["username"]);
}
else
{
return;
}
}
But I cannot run method? So how do I fix it?
you can use below mentioned code.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
MyMethod();
MyMethod1();
}
public async Task MyMethod()
{
Task<int> longRunningTask = LongRunningOperation();
//indeed you can do independent to the int result work here
//and now we call await on the task
int result = await longRunningTask;
//use the result
MessageBox.Show(result.ToString());
}
public async Task MyMethod1()
{
Task<int> longRunningTask = SecondMethod();
//indeed you can do independent to the int result work here
//and now we call await on the task
int result = await longRunningTask;
//use the result
MessageBox.Show(result.ToString());
}
public async Task<int> LongRunningOperation() // assume we return an int from this long running operation
{
await Task.Delay(5000); //5 seconds delay
return 1;
}
public async Task<int> SecondMethod()
{
await Task.Delay(2000);
return 1;
}

Categories