I use this simple c# code (ok, the result is a little bit silly but it's just to try to solve my problem) to fill a grid (a Syncfusion Blazor datagrid which reads the _monitoringDatas variable to fill out ) :
namespace ligprod.Client.Pages
{
public partial class Monitoring_ligne
{
...
private Monitoring Monit;
private List<Monitoring> _monitoringDatas;
protected override async Task OnInitializedAsync()
{
...
_monitoringDatas = new List<Monitoring>();
}
Task ReceiveLidarValue(string arg)
{
_monitoringDatas = new List<Monitoring>();
Monitoring Monit = new Monitoring()
{
IdMonotoring = 1,
RealProduction = false,
Machine = "remplisseuse",
DatePassage = DateTime.Now,
};
_monitoringDatas.Add(Monit);
}
}
Why do I have to instantiate _monitoringDatas into the ReceiveLidarValue(string arg) task to make the grid filled whereas it was already instantiated in the OnInitializedAsync() Task ?
Yet, the OnInitializedAsync() Task is reached correctly. Indeed, it also contains code to get values from a Hub which works well.
ReceiveLidarValue() is called each time a particular message is thrown to a hub from a service which receive mqtt messages coming from an external electronic card which have a sensor for movements detection :
1/ Server side > As soon as the application is started the service runs and waits for messages from the electronic card.
2/ Client side > The web page (shown in my demand above) is started in a browser (manually). The OnInitializedAsync() method is called and so,-monitoringDatas is instantiated.
3/ Server side > Each time a movement is detected by the sensor, a message (with mqtt protocol) is sent by the electronic card and is finally read by the service which then send a particular message into a hub.
4/ Client side > The message into the hub is detected by the web page and the ReceiveLidarValue(string arg) Task is called.
5/ This Task build a new Monitoring object called Monit (which normally contains an Id, a bool value, the name of the machine on which the movement is detected and the date of detection). This "Monit" is added to the datagrid.
So, each time a new movement is detected, the *ReceiveLidarValue(string arg)*Task is launched and a new Monitoring object is created and added to the datagrid.
All this process works well, but If I comment or erase the _monitoringDatas = new List<Monitoring>(); instantiation into the ReceiveLidarValue(string arg) Task, the grid is not filled (without any error). And Of course, if I leave this second instantiation in the code, the datagrid will be filled but it will always contain only one line replacing the previous one instead of having the new line written after the previous one.
You haven't explained where ReceiveLidarValue gets called, so it's possible it's being called before OnInitializedAsync() is called. You also didn't explain why you think you have to instantiate _monitoringDatas twice. If you are receiving a null ref exception, then my comment above is probably correct. If not, please fill in more details.
Related
I want to have my app open up every single time the device is unlocked. Effectively, I need a consistent replacement for ACTION_USER_PRESENT.
(NOTE THIS IS FOR AN INTERDISCIPLINARY, PEER-REVIEWED ACADEMIC STUDY STARTING SOON AND IS VITAL FOR THE STUDY'S SUCCESS)
Before the Oero 8.0 update, ACTION_USER_PRESENT was a perfect way to start up the android app each time the device was unlocked.
Unfortunately the work-arounds I've been trying to use are just not cutting it. Effectively I've assigned a myBroadastReceiver to attempt to run the app and PowerManager to see if the device is on or not. Depending on if the device is being used will impact if in the myBroadcastReceiver code will Initiate an Intent.
Problem 1) The broadcast receiver can only be assigned to run at minimum every 15 minutes. I need it to run every time the device unlocks.
Problem 2) Sometimes the broadcast receiver doesnt even try to run for hours at a time... as if the assigned 15 minute check is more of a loose suggestion and not an explicit command.
SOME CODE:
public class classMyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context contextOfReceive, Intent intentOfReceive) {
////////////////////////////////////////////////////////////////////////////////////////////
//This loads up the user selected settings choosen at the homepage of the application.
final SharedPreferences internalAppInformation = contextOfReceive.getSharedPreferences("userPreferences", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = internalAppInformation.edit();
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
//Code used to determine 2 things
// 1) if the Device being used or inactive
// 2) if the activity has already been prompted earlier and therefore should be in the foreground of the device
PowerManager pm = (PowerManager) contextOfReceive.getSystemService(Context.POWER_SERVICE);
boolean booleanIsScreenOn = pm.isInteractive();
boolean booleanIsActivityUp = internalAppInformation.getBoolean("booleanIsActivityUp", false);
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
//If Screen is Off (i.e. the device is NOT BEING USED AT THE MOMENT)
//then this code should allow the Activity to Start
if ( (!booleanIsActivityUp)&&(!booleanIsScreenOn) ) {
//Initiates and Starts up the Intent PromptAndClose.class
editor.putBoolean("booleanIsActivityUp", true);
editor.commit();
editor.apply();
//THE REST OF THE CODE BELOW IS JUST CHOOSING AND
// INITIATING THE PROGRAM AND IS NOT PROBLEMATIC.
}
}
More detailed code can be provided if it will be helpful. I am worried that more code will result it too much clutter for the reader.
ADDITIONAL CODE TO DESCRIBE WHEN THE myBroadcastReceiver is Initiated.
public class Settings extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
////////////////////////////////////////////////////////////////////////////////////////////
//Sets up and starts the calendar (with the setAlarm method for re-occuring attempts to
//prompt the app to move to the foreground if the right conditions are met.
Calendar calendar = Calendar.getInstance();
//if(Build.VERSION.SDK_INT >= 23) {
Log.i("Calendar", "Set Calendar >=23");
calendar.set(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
calendar.get(Calendar.HOUR),
calendar.get(Calendar.MINUTE),
30
);
setAlarm(calendar.getTimeInMillis());
int time = (int) calendar.getTimeInMillis();
String timeString = String.valueOf(time);
Log.i("TIME", "time: " + timeString);
}
private void setAlarm(long timeInMillis) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, classMyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
assert alarmManager != null;
//RTC-Fires the pending intent at the specified time but does not wake up the device.
//The shortest interval is INTERVAL_FIFTEEN_MINUTES.
alarmManager.setInexactRepeating(AlarmManager.RTC, timeInMillis,
AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
}
}
This code is present in the main activity of the application. The concept is that the first time the app is installed and ran, it will run this code and start and continuous loop of checking and displaying the app to the foreground of the device if the device is not being used. Once that intent is interacted with by the user and closed, the loop starts up again.
That is not going to work. Doze mode and app standby will make what you are trying to do very unreliable.
Try this: Create a foreground service. Start that foreground service when you need to start receiving this broadcast. In onCreate() of that service, call registerReceiver() register a receiver for ACTION_USER_PRESENT. So long as your service is running, you will receive the ACTION_USER_PRESENT broadcast as before.
works here -----
crashes here -----
So i am making this server client chat system based on message queue and in client side, i have a thread that receives messages. The name of my listbox is 'displaymsg'
here's my thread pool method
public void getmsg(object ob)
{
string msg = "";
while (true)
{
msg = mRecieve.GetMessages();
displaymsg.Items.Add(msg);
}
}
But the program is crashing when it reaches to displaymsg.Items.Add(msg) part.
To check if it is even reaching there and if it is working fine, i replaced it with MessageBox.Show(msg), and it is working fine, i receive every message in a pop up box that i send from other end. I'm new to wpf so kinda lost now... please help!!
You can not access a control from a non-UI thread. You have to use a dispatcher to marshal it back to the UI thread:
displaymsg.Dispatcher.Invoke(() => displaymsg.Items.Add(msg));
You can also fire and forget if you don‘t want to wait for the result:
displaymsg.Dispatcher.BeginInvoke(() => displaymsg.Items.Add(msg));
I am attempting to call/push a semi-large tiff and a Gal file to a java webservice.
The platform is Visual Studio 2013, C# windows forms application.
I am pointing to the WSDL file and "The Platform" is generating a service reference class for me.
This is all very abstracted from me, which is a good thing as I am a relative newbie to this arena.
I left the "Generate Task based Code" checked and I get an addSample and addSampleAsync method.
I populate the class fields and push the code up.
The addSample code works fine but blocks the UI.
The async code, addSampleAsync, also works, bit is slower and is not completely asynchronous.
addSampleAsync locks the UI for about half of the processing time and the function call to fncTestUpload does not return for that same period of time.
//Dimensioned at class level
//private static addSamplePortClient Service = new addSamplePortClient();
//private static addSampleResponse Myresult = new addSampleResponse();
//ThisRequest is the WSDL modeled class object.
//This code works, but is slow, 30 seconds on wifi
ResponseType Myresult = Service.addSample(ThisRequest.Request);
MessageBox.Show(Myresult.Message + Myresult.Code);
//This code locks up the UI for about 15 - 20 seconds then takes another 15 to display the messagebox
fncTestUpload(ThisRequest);
async void fncTestUpload(addSampleRequest SentRequest)
{
Myresult = await Service.addSampleAsync(SentRequest.Request);
MessageBox.Show(Myresult.Response.Message + " - " + Myresult.Response.Code);
}
I made the response object a class level variable in hopes of doing something with it in the function that calls fncTestUpload, which it thought would return immediately when calling an Async function. It does not return until after 15 seconds.??
I have spent several hours googling this and have not found any answers as to why the addSampleAsync is not working as advertised.
Microsoft's tutorials may as well be written in Dilbert's Elbonian. I can't follow them and don't find them helpful, so please don't direct me to one.
When you use the 'await' keyword in your method you are saying "Ok, you go ahead and do work, I will return to my caller, let me know when you're done".
So the 15 seconds of waiting is the time it takes your service to process the request, then invoking the state machine generated by the async method to return to the method after the previously awaited method has finished. That is the normal behavior for await.
About the MessageBox that is taking 15 seconds, it could be that the Response property is lazyloading and actually trying to load the code / message for the first time wheb you access those properties.
We are developing an application using the LeapMotion SDK in VS2012 Express for desktop using C#.
Therein we add a listener thread to the Leap Controller object.
As so:
Controller objcontroller = new Controller();
Listener objlistener = new LeapListener();
objcontroller.AddListener(objlistener);
The controller object does a callback of overridden methods like OnFrame() etc.
The problem is the listener thread exits automatically after certain number of callbacks which range from 3000 to 5500. The output window shows the following text:
The thread (0x1614) has exited with code 0 (0x0).
LeapMotion is a motion detection device which reports frames at a rate of upto 100 fps. When a frame is detected the OnFrame() method gets called.
We tried using try catch.. and no exceptions are thrown - since exit code is 0.
I feel the memory consumption is getting exceeded which causes the compiler to shutdown the thread.
Any ideas on this would be helpful.
Platform target is x86 and .net framework target is 4.0
There is a related question which I answered here:
Leap Listener controller stops working after some time in VS2012
Simply put: your controller and listener objects go out of scope and get disposed by the GC.
Its actually a problem with the WPF and Leap code.
In this case I simply reassigned the controller on Exit of the Listener. I declared a Listener object globally in my class as
public static Listener objlistener;
public static Controller controller;
And add this on the onExit() event
public override void OnExit(Controller controller)
{
objlistener = new LeapListener();
controller.AddListener(objlistener);
}
In my C# Windows Forms application , I retrieve some data from WebServices over the Internet. Refresh every second
It works as asynchronous operations and works well but whenever application gets disconnected from Internet, it shows an exception, and when it reconnects to the Internet, program should work automatically and immediately.
Currently, the program takes more then one minute to start working again, and I would like the exception to be ignored when connection drops.
it refreshed every second , it mean there are plenty of threads running at same time and
when they all done , then it comes to connecting
What solution i can use so my programs runs ASAP when internet connects?
public void loadbalance()
{
try { //Get Data from Internet }
catch { }
}
delegate void loadbalancedelegate();
public void loadBalanceAsync()
{
loadbalancedelegate worker = new loadbalancedelegate(loadbalance);
AsyncCallback LoadbalnceCallBack = new AsyncCallback(loadbalanceCompleted);
AsyncOperation async = AsyncOperationManager.CreateOperation(null);
worker.BeginInvoke(LoadbalnceCallBack,async);
}
public void loadbalanceCompleted(IAsyncResult result)
{
loadbalancedelegate worker = (loadbalancedelegate) ((AsyncResult)result).AsyncDelegate;
AsyncOperation async = (AsyncOperation)result.AsyncState;
worker.EndInvoke(result);
}
delegate void setControlsBalanceDelegate(BalanceOB ball);
void setControlsBalance(BalanceOB ball)
{
if (this.InvokeRequired)
this.Invoke(new setControlsBalanceDelegate(this.setControlsBalance), new
object[] { ball });
else
{ //Update Data on Form (Windows App)
}
}
I would probably do the following:
In your timer code which runs every second, I would check if the internet connectivity is available by P/Invoke (which is faster way than having the service throw an exception, and looks like it would suit your cause as well). For some reference look here
I would have the P/invoke code also set a flag temporarily somewhere (make sure it is thread safe) and before making any web service calls, i would check if the flag is in a valid state for the client to make that call.