When app goes background the thread pause - multithreading

I need your help.
I have a chronometer app very simply that show the time running.
I created a thread that count the time and update the UI.
When the app is in first plane, everything is fine.
When I press back buttom the app goes background but the Thread is paused for the system.
When I return to the App, the chronometer began to run again.
How I can do for maintenance the time running on background?
I will appreciate your hep.
Thanks,
Rodrigo.
private void cronometro(){
new Thread(new Runnable(){
#Override
public void run() {
while (true) {
if (isOn) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
mensaje_log = "Se produjo un error";
Log.d("Miapp",mensaje_log);
Escribirlog.escribir_eventos(mensaje_log);
mensaje_log = e.getMessage();
Escribirlog.escribir_eventos(mensaje_log);
Thread.currentThread().interrupt();
}
mili++;
if (mili == 999) {
seg++;
mili = 0;
saltos++;
if (saltos == 10) {
//escribe log cada 10 segundos
mensaje_log = "Corriendo...";
Log.d("Miapp",mensaje_log);
Escribirlog.escribir_eventos(mensaje_log);
saltos = 0;
}
}
if (seg == 59) {
minutos++;
seg = 0;
}
h.post(new Runnable() {
#Override
public void run() {
String m = "", s = "", mi = "";
if (mili < 10) {
m = "00" + mili;
} else if (mili < 100) {
m = "0" + mili;
} else {
m = "" + mili;
}
if (seg < 10) {
s = "0" + seg;
} else {
s = "" + seg;
}
if (minutos < 10) {
mi = "0" + minutos;
} else {
mi = "" + minutos;
}
m = m.substring(0,2); //toma los 2 primeros numeros de milisegundos
crono.setText(mi + ":" + s + ":" + m);
}
});
}
}
}
}).start();
}

In order to keep a task running in the background in flutter you will need to use a package, a one you can go with is https://pub.dev/packages/background_fetch, the way you going to use it like this:
void backgroundFetchHeadlessTask(HeadlessTask task) async {
String taskId = task.taskId;
bool isTimeout = task.timeout;
if (isTimeout) {
// This task has exceeded its allowed running-time.
// You must stop what you're doing and immediately .finish(taskId)
print("[BackgroundFetch] Headless task timed-out: $taskId");
BackgroundFetch.finish(taskId);
return;
}
print('[BackgroundFetch] Headless event received.');
// Do your work here...
BackgroundFetch.finish(taskId);
}
And then you will have to call it inside your main
void main() {
runApp(new MyApp());
BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
}
And finally call it when you need it to start fetching this way:
BackgroundFetch.start().then((int status) {
print('[BackgroundFetch] start success: $status');
}).catchError((e) {
print('[BackgroundFetch] start FAILURE: $e');
});
} else {
BackgroundFetch.stop().then((int status) {
print('[BackgroundFetch] stop success: $status');
});

Related

C# Threads wont work when i show form with form.ShowDialog

MyForm myForm = new MyForm();
myForm.ShowDialog();
In the MyFormClass
private void MyForm_Load(object sender, EventArgs e)
{
nameLabel.Text = user.username;
waitForServerMsgThread = new Thread(() => {
Thread.CurrentThread.IsBackground = true;
AddMessage("Start of this thread");
try
{
stream = client.GetStream();
while (true)
{
AddMessage(client.Available.ToString());
if (client.Available > 0)
{
byte[] byteToRead = new byte[client.Available];
stream.Read(byteToRead, 0, byteToRead.Length);
MessageToClient message = (MessageToClient)Commands.FromBytes(byteToRead);
if (message.messageType == MessageToClient.MessageType.IncoimgMessage)
{
MessageFromPerson msg = (MessageFromPerson)message.Message;
AddMessage(msg.name + " says: " + msg.msg);
}
}
}
}
catch (Exception ex)
{
AddMessage("Could not load data from server error " + ex.ToString());
}
});
waitForServerMsgThread.Start();
FormClosing += (s, args) => waitForServerMsgThread.Abort();
}
And it wont even execute the thread no matter if put Thread.Start in _Load or When button is pressed.And no i cant load form with myForm.Show(); because it wont show it will close after i call it(ShowDialog() is called from Thread)

Sound won't play at a specific time in unity

I am trying to make a sound play with the timer goes to 3, 2, 1.
My timer starts at ten and has a three second delay. If I use the following code:
if (tl.myCoolTimer == 10)
{
print("Play Sound");
myAudioSource.Play();
}
It plays the Beep over and over again until the game starts and the counter goes below 10.
If I use the code:
if (tl.myCoolTimer == 3)
{
print("Play Sound");
myAudioSource.Play();
}
It doesn't play the sound at all. It doesn't even print the print statement.
I literally only changed the number. I am not sure why this isn't working.
I have also tried setting it to 3f to see if it is a float issue.
Timer Scripts
This is the starting Timer. it counts down to 3 (then the game starts)
public Text startGameTimerText;
public float startGameTimer = 3;
public void Start ()
{
startGameTimerText = GetComponent<Text> ();
}
public void Update ()
{
startGameTimer -= Time.deltaTime;
startGameTimerText.text = startGameTimer.ToString ("f1");
if (startGameTimer < 0) {
GameObject.Find ("GameStartTimer").SetActive (false);
}
}
This is the Game Timer It starts at 10 and counts down to 0.
public StartGameTimer gt; //this is the script the other timer is on
public Text timerText;
public float myCoolTimer = 10;
public void Start ()
{
timerText = GetComponent<Text> ();
}
public void Update ()
{
if (gt.startGameTimer > 0) {
myCoolTimer = 10;
} else {
myCoolTimer -= Time.deltaTime;
timerText.text = myCoolTimer.ToString ("f1");
}
}
Thanks Joe for the help. Here was my final answer. I know it is hacked, but I haven't figured out the Invoke thing yet. When I set the into it kept playing the entire time it was at "3", so i need to make it play only once.
private AudioSource myAudioSource;
public bool isSoundPlayed;
void Start()
{
myAudioSource = GetComponent<AudioSource>();
isSoundPlayed = false;
}
void Update()
{
if((int)tl.myCoolTimer == 3)
{
if (isSoundPlayed == false)
{
myAudioSource.Play();
isSoundPlayed = true;
}
return;
}
if ((int)tl.myCoolTimer == 2)
{
if (isSoundPlayed == true)
{
myAudioSource.Play();
isSoundPlayed = false;
}
return;
}
if ((int)tl.myCoolTimer == 1)
{
if (isSoundPlayed == false)
{
myAudioSource.Play();
isSoundPlayed = true;
}
return;
}
}

This program is not being stop after pressing c

This program is not being stop after pressing c.
This program should stop after pressing c but it is not.
I am searching .dll file in given directory. After that I am searching given method name and property
by user.
class Program
{
static void Main(string[] args)
{
char choice;
Console.WriteLine(AppConst.Messages.UserChoice);
Console.WriteLine(AppConst.Messages.Star);
choice = GetResponse();
string name = string.Empty;
if (choice == 'M')
{
Console.WriteLine(AppConst.Messages.InputMethodName);
name = Console.ReadLine();
}
if (choice == 'P')
{
Console.WriteLine(AppConst.Messages.InputPropertyName);
name = Console.ReadLine();
}
CancellationTokenSource cancellationToken = new CancellationTokenSource();
// Use ParallelOptions instance to store the CancellationToken.
ParallelOptions parallelOption = new ParallelOptions();
parallelOption.CancellationToken = cancellationToken.Token;
parallelOption.MaxDegreeOfParallelism = 10;
Console.WriteLine(AppConst.Messages.StartSearchingMessage);
Console.ReadKey();
//Console.WriteLine();
// Run a task so that we can cancel another thread.
Task.Factory.StartNew(() =>
{
while (Console.ReadKey().Key != ConsoleKey.C) ;
cancellationToken.Cancel();
});
int countClass = 0;
string[] files = Directory.GetFiles(#"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5", "*.dll");
try
{
Parallel.ForEach(files, parallelOption, (file) =>
{
parallelOption.CancellationToken.ThrowIfCancellationRequested();
try
{
var asm = Assembly.LoadFile(file);
foreach (var type in asm.GetTypes())
{
if (choice == 'M')
{
try
{
MethodInfo methodInfo = type.GetMethod(name);
if (methodInfo != null)
{
countClass++;
Console.WriteLine(AppConst.Messages.Star);
Console.WriteLine(AppConst.Messages.
PrintFileName, Path.GetFileName(file));
Console.WriteLine(AppConst.Messages.
PrintCalssName, type.Name);
}
}
catch (AmbiguousMatchException ex)
{
Console.WriteLine("\n{0}\n{1}", ex.GetType().
FullName, ex.Message);
}
}
if (choice == 'P')
{
try
{
PropertyInfo propertyInfo = type.GetProperty(name);
if (propertyInfo != null)
{
countClass++;
Console.WriteLine(AppConst.Messages.Star);
Console.WriteLine(AppConst.Messages.
PrintFileName, Path.GetFileName(file));
Console.WriteLine(AppConst.Messages.
PrintCalssName, type.Name);
}
}
catch (NullReferenceException e)
{
Console.WriteLine(AppConst.Messages.
PropertyNotExist + e.Message);
}
}
}
}
catch (BadImageFormatException e)
{
Console.WriteLine(AppConst.Messages.UnableTOLoad,
Path.GetFileName(file));
Console.WriteLine(e.Message.Substring(0, e.Message.IndexOf(".") + 1));
}
//parallelOption.CancellationToken.ThrowIfCancellationRequested();
});
}
catch (OperationCanceledException e)
{
Console.WriteLine(e.Message);
}
catch (Exception e)
{
Console.WriteLine();
Console.ReadLine();
}
if (countClass == 0)
{
Console.WriteLine(AppConst.Messages.NotExistMessage);
}
Console.ReadKey();
}
private static char GetResponse()
{
char response;
while (true)
{
//Checking for entered input is M or P.
if (Char.TryParse(Console.ReadLine().ToUpper(), out response)
&& (response == 'M' || response == 'P'))
break;
//AppConst.Messages.InvalidChoice is string message.
Console.WriteLine(AppConst.Messages.InvalidChoice);
}
return response;
}
}
It seems to me that the main problem in your code is that you only check for cancellation once, right when a thread starts. If you want an exception, or any other type of cancellation for that matter, you need to actually check the CancellationToken somehow while you're running the task.
It looks to me as though you would want to put the parallelOption.CancellationToken.ThrowIfCancellationRequested(); line in the loop block for the foreach (var type in asm.GetTypes()) loop, probably as the first statement in the block.
Here is a simple example demonstrating correct use of CancellationToken in a way that is similar to what you seem to want:
CancellationTokenSource tokenSource = new CancellationTokenSource();
Thread thread = new Thread(() =>
{
while (Console.ReadKey().Key != ConsoleKey.C) { }
tokenSource.Cancel();
});
thread.IsBackground = true;
thread.Start();
TimeSpan[] timeSpans = new TimeSpan[10];
int completedCount = 0;
timeSpans[0] = TimeSpan.FromSeconds(4);
for (int i = 1; i < timeSpans.Length; i++)
{
timeSpans[i] = timeSpans[i - 1] + TimeSpan.FromSeconds(2);
}
try
{
Parallel.ForEach(timeSpans, timeSpan =>
{
Stopwatch sw = Stopwatch.StartNew();
while (sw.Elapsed < timeSpan)
{
Thread.Sleep(100);
tokenSource.Token.ThrowIfCancellationRequested();
}
Console.WriteLine("Completed {0} threads (thread time: {1})",
Interlocked.Increment(ref completedCount), sw.Elapsed);
});
}
catch (AggregateException e)
{
Console.WriteLine("Exception: " + e);
}
Console.WriteLine("All threads completed");
Note that the exception actually seen in the main thread is an AggregateException. This contains the individual exception information for each thread that was cancelled.

Error while adding entity object to DBContext object called from Parallel.Foreach loop

Error :
If the event originated on another computer, the display information had to be saved with the event.
The following information was included with the event:
Object reference not set to an instance of an object. at
System.Data.Objects.ObjectStateManager.DetectConflicts(IList1
entries) at System.Data.Objects.ObjectStateManager.DetectChanges()
at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean
force) at
System.Data.Entity.Internal.Linq.InternalSet1.ActOnSet(Action action,
EntityState newState, Object entity, String methodName) at
System.Data.Entity.Internal.Linq.InternalSet1.Add(Object entity)
at System.Data.Entity.DbSet1.Add(TEntity entity) at
ESHealthCheckService.BusinessFacade.BusinessOperationsLayer.AddErrorToDbObject(Exception
ex, Server serverObj, Service windowsServiceObj)
the message resource is present but the message is not found in the string/message table
public void CheckForServerHealth()
{
businessLayerObj.SetStartTimeWindowsService();
List<ServerMonitor> serverMonitorList = new List<ServerMonitor>();
serverList = businessLayerObj.GetServerList();
Parallel.ForEach(
serverList,
() => new List<ServerMonitor>(),
(server, loop, localState) =>
{
localState.Add(serverStatus(server, new ServerMonitor()));
return localState;
},
localState =>
{
lock (serverMonitorList)
{
foreach (ServerMonitor serverMonitor in localState)
{
serverMonitorList.Add(serverMonitor);
}
}
});
businessLayerObj.SaveServerHealth(serverMonitorList);
}
public ServerMonitor serverStatus(Server serverObj, ServerMonitor serverMonitorObj)
{
if (new Ping().Send(serverObj.ServerName, 30).Status == IPStatus.Success)
{
serverMonitorObj.Status = true;
try
{
PerformanceCounter cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total", serverObj.ServerName);
serverMonitorObj.CPUUtlilization = (cpu.NextValue());
}
catch (Exception ex)
{
businessLayerObj.AddErrorObjectToStaticList(ex, serverObj);
}
serverMonitorObj.ServerID = serverObj.ServerID;
try
{
string[] diskArray = serverObj.DriveMonitor.ToString().Split(':');
if (diskArray != null && diskArray.Contains("NA"))
{
serverMonitorObj.DiskSpace = "NA";
}
else
{
serverMonitorObj.DiskSpace = ReadFreeSpaceOnNetworkDrives(serverObj.ServerName, diskArray);
}
}
catch (Exception ex)
{
businessLayerObj.AddErrorObjectToStaticList(ex, serverObj);
}
serverMonitorObj.CreatedDateTime = DateTime.Now;
}
else
{
serverMonitorObj.Status = false;
serverMonitorObj.ServerID = serverObj.ServerID;
//return serverMonitorObj;
}
return serverMonitorObj;
}
public void AddErrorObjectToStaticList(Exception ex, Server serverObj = null, Service windowsServiceObj = null)
{
EShelathLoging esLogger = new EShelathLoging();
esLogger.CreateDatetime = DateTime.Now;
if (ex.InnerException != null)
{
esLogger.Message = (windowsServiceObj == null ? ex.InnerException.Message : ("Service Name : " + windowsServiceObj.ServiceName + "-->" + ex.InnerException.Message));
//esLogger.Message = "Service Name : " + windowsServiceObj.ServiceName + "-->" + ex.InnerException.Message;
esLogger.StackTrace = (ex.InnerException.StackTrace == null ? "" : ex.InnerException.StackTrace);
}
else
{
esLogger.Message = (windowsServiceObj == null ? ex.Message : ("Service Name : " + windowsServiceObj.ServiceName + "-->" + ex.Message));
//esLogger.Message = "Service Name : " + windowsServiceObj.ServiceName + "-->" + ex.Message;
esLogger.StackTrace = ex.StackTrace;
}
if (serverObj != null)
{
esLogger.ServerName = serverObj.ServerName;
}
try
{
lock (lockObject)
{
esHealthCheckLoggingList.Add(esLogger);
}
}
catch (Exception exe)
{
string logEntry = "Application";
if (EventLog.SourceExists(logEntry) == false)
{
EventLog.CreateEventSource(logEntry, "Windows and IIS health check Log");
}
EventLog eventLog = new EventLog();
eventLog.Source = logEntry;
eventLog.WriteEntry(exe.Message + " " + exe.StackTrace, EventLogEntryType.Error);
}
}
And then the below function is called to add objects from static list to the db object.
public void AddErrorToDbObject()
{
try
{
foreach (EShelathLoging eslogObject in esHealthCheckLoggingList)
{
lock (lockObject)
{
dbObject.EShelathLogings.Add(eslogObject);
}
}
}
catch (DbEntityValidationException exp)
{
string logEntry = "Application";
if (EventLog.SourceExists(logEntry) == false)
{
EventLog.CreateEventSource(logEntry, "Windows and IIS health check Log");
}
EventLog eventLog = new EventLog();
eventLog.Source = logEntry;
eventLog.WriteEntry(exp.Message + " " + exp.StackTrace, EventLogEntryType.Error);
}
catch (Exception exe)
{
string logEntry = "Application";
if (EventLog.SourceExists(logEntry) == false)
{
EventLog.CreateEventSource(logEntry, "Windows and IIS health check Log");
}
EventLog eventLog = new EventLog();
eventLog.Source = logEntry;
eventLog.WriteEntry(exe.Message + " " + exe.StackTrace, EventLogEntryType.Error);
}`enter code here`
}
DbSet<T> is not thread-safe, so you can't use it from multiple threads at the same time. It seems you're trying to fix that by using a lock, but you're doing that incorrectly. For this to work, all threads have to share a single lock object. Having separate lock object for each thread, like you do now, won't do anything.
Please note that I received the same exception with the application I was working on, and determined that the best way to resolve the issue was to add an AsyncLock, because of what #svick mentioned about how DbSet is not threadsafe. Thank you, #svick!
I'm guessing that your DbContext is inside your businessLayerObj, so here is what I recommend, using Stephen Cleary's excellent Nito.AsyncEx (see https://www.nuget.org/packages/Nito.AsyncEx/):
using Nito.AsyncEx;
// ...
private readonly AsyncLock _dbContextMutex = new AsyncLock();
public void CheckForServerHealth()
{
using (await _dbContextMutex.LockAsync().ConfigureAwait(false))
{
await MyDbContextOperations(businessLayerObj).ConfigureAwait(false);
}
}
private async Task MyDbContextOperations(BusinessLayerClass businessLayerObj)
{
await Task.Run(() =>
{
// operations with businessLayerObj/dbcontext here...
});
}

The need for the multithreading in javafx

I'm new to javafx and I have a question. My project is a voice browser with some simple command but I have an issue in switch(). The command at lines one and three of first case statement work, but line 2 does not. But if I remove the while loop, it works well! I have no idea how to solve this, help me please!
Here is my code
btSpeak.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
new Task<Void>(){
public Void call(){
int click=JOptionPane.showConfirmDialog(null, "Bạn đã sẵn sàng trải nghiệm với VoiceCommand chưa", "Speak", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(click==JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null, "Start", "Speak", JOptionPane.INFORMATION_MESSAGE);
// code for voice recognize
try {
URL url;
url = HelloWorld.class.getResource("helloworld.config.xml");
System.out.println("Loading..."+url.toString());
ConfigurationManager cm = new ConfigurationManager(url);
final Recognizer recognizer = (Recognizer) cm.lookup("recognizer");
Microphone microphone = (Microphone) cm.lookup("microphone");
/* allocate the resource necessary for the recognizer */
recognizer.allocate();
/* the microphone will keep recording until the program exits */
if (microphone.startRecording())
{
System.out.println("Say: (Leen | Xuoongs| Trais | Phair | DDi |Veef| Dongs-Tab|Mowr-Tab| Noi - Dung| Trang-Chur|Trang-Truoc)") ;
System.out.println("Start speaking. Press Ctrl-C to quit.\n");
/*
* This method will return when the end of speech
* is reached. Note that the endpointer will determine
* the end of speech.
*/
// Platform.runLater(new Runnable(){
// public void run(){
int i = 0;
while(i< 5) {
//Thread.this.notifyAll();
Result result = recognizer.recognize();
if (result != null)
{
int t = 0;
System.out.println("Enter your choise"+ "\n");
resultText = result.getBestFinalResultNoFiller();
System.out.println("You said: " + resultText + "\n");
if(resultText.equals("xuoongs")) {
t = 1;
} else if(resultText.equals("leen")) {
t = 2;
}
switch(t) {
case 1: {
JOptionPane.showMessageDialog(null, "xuống");//line 1
webEngine.executeScript("window.scrollBy(0,100)");line 2
break;// line 3
}
case 2: {
JOptionPane.showMessageDialog(null, "lên");
webEngine.executeScript("window.scrollBy(0,-100)");
break;
}
}// end switch
}// end if
}//end while()
}// end if
} catch (PropertyException e) {
System.err.println("Problem configuring HelloWorld: " + e);
e.printStackTrace();
}
}
}
}.run());
}// end button
});

Resources