I am pretty new to windows service and I am trying to install a service to run some code (that I did not write).
This code runs without problem ( not in service mode) but when I install the service and try to run the service I have a timeout Error 1053 (The Service did not Respond to the Start or Control Request in a Timely Fashion).
I tried to set the ServicePipeTimeout to a higher value and install my service in release mode but that does not change anything.
After some investigations and prints I get an error with the main function Static Async Task()
So I am asking myself if maybe there is an incompatibility between Async and service ?
For example Maybe this kind of code executed at the beginning, could provoke timeout I get when I start my service: (I just wanted to know if async and service was compatible to help me in my search).
static void Main(string[] _)
{
MainAsync().Wait();
}
private static async Task MainAsync()
{
TimeSpan timeSpan = new TimeSpan(0, 0, 30);
using (SftpWatcher watcher = new SftpWatcher(mailServer, mailSender, mailName, mailDestination, ...)
{
await watcher.Start(timeSpan);
}
}
Related
I have searched too much and read too many posts about this problem.
The scenario of my app is to listen VOIP server event logs and send these logs to clients with SignalR. It works properly until event logs finished at the end of the day but at beginning the next day it won't start again.
I tried both Background Service with ExecuteAsync and IHostedService with StartAsync but it doesn't changed the result.
Here is the AppPool settings for my app on iis.
If I stop/start the app's site on IIS and open it in browser on server it will starts again.
Is it a known issue in Asp.Net background service?
Any idea would be appreciated.
Best way for keep your service live in IIS is create an ping service and call an GET HTTP request every 10 sec your home page.
IIS keep live your app base on request and if your app has not any request it will shotdown it.
create an Pinger background service and call your self!
simple ping service:
public class Pinger : BackgroundService
{
private readonly ILogger<Pinger> _logger;
public Pinger(ILogger<Pinger> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
using (var httpClient = new HttpClient())
{
await httpClient.GetAsync("https://sample.com/", stoppingToken);
_logger.LogInformation($"Ping at {DateTime.UtcNow:s}");
}
await Task.Delay(10 * 1000, stoppingToken);
}
}
}
in program.cs
Host.CreateDefaultBuilder(args)...
.ConfigureServices(services =>
{
services.AddHostedService<Pinger>();
});
I have a method on the sample content page (sample.XAML.cs) and I want to set this method in a timer and run every 10 seconds even after the app is killed or closed.
public async void AlarmStart()
{
HttpClient client = new HttpClient();
HttpResponseMessage response = client.GetAsync("JsonFile").Result;
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<OnlineValueClass>>(content);
}
}
In Android, starting in Android 8.0 (API level 26), an Android application no longer have the ability to run freely in the background. For more details about this, you can refer to Background Execution Limits in Android 8.0:
But you can try to restarted the service once it been finished by a BroadcastReceiver . The function of BroadcastReceiver is to receive a signal when someone or something kills the service; its role is to restart the service.
For more details, you can check an relative article by entering key words
Creating a never ending background service in Android. Though it's Java code, it's easy to understand and convert
I'm having hard time with this one.
So in my asp.net application there is such a method:
public CopyResponse thirdStage(CopyRequest request)
{
CopyCCResponse response = new CopyCCResponse();
Task.Run(() =>
{
performCopying(request);
});
return response;
}
private void performCopying(CopyCCRequest request)
{
using (Repository = new myDbContext())
{
// do some initial action
try
{
// in general it looks like below
foreach(var children in father)
{
var newChildren = chldren.Copy();
Repository.Childrens.Add(newChildren);
foreach (var grandchldren in children.grandchildrens)
{
var newGrandchildren = grandchldren.Copy();
newGrandchildren.Parent = newChildren;
Repository.Grandchildrens.Add(newGrandchildren);
}
Repository.SaveChanges();
}
}
catch (Exception ex)
{
// log that action failed
throw ex;
}
}
}
This method and all other (there are some similar) works as designed on my local computer without any problems.
Unfortunately, on another environment those methods fail:
Copying smaller parts of data works fine. But when there is over 3000 objects to operate on, method fails.
Main application is responding correctly nevertheless.
Most of the operation is done well (most data is copied and saved in database)
Application doesn't enter catch block. Instructions for failed copying are not executed. Exception isn't caught by the error handler (BTW, I know by default the app can't catch exceptions from independent task, I wrote my handler so it will manage to do so).
IIS worker process seems to take over 300MB and 0% of processor power after copying stopped. More than half of RAM on server is still free.
I looked into windows event log, but haven't found anything.
Do you have any suggestions how I can handle this issue?
You can't do reliable "Fire and forget" tasks from inside IIS, if the site is not being served the application pool will get its AppDomain shut down after a while.
Two options to use are:
HostingEnvironment.QueueBackgroundWorkItem to tell IIS you are doing background work. This will let the server know of the work and it will delay the shutdown as long as it can (default up to 90 seconds max) before it kills your process.
public CopyResponse thirdStage(CopyRequest request)
{
CopyCCResponse response = new CopyCCResponse();
HostingEnvironment.QueueBackgroundWorkItem(() =>
{
performCopying(request);
});
return response;
}
Another option is to use a 3rd party library that is designed for doing background work in IIS like Hangfire.io, this will run a service inside of IIS that does the work and attempts to keep the instance alive till the work is done. You can also configure Hangfire to run as a separate process so you don't need to rely on the lifetime of the IIS instance.
public CopyResponse thirdStage(CopyRequest request)
{
CopyCCResponse response = new CopyCCResponse();
BackgroundJob.Enqueue(() =>
{
performCopying(request);
});
return response;
}
Note, using hangfire with a seperate process may require you to do a little redesign of performCopying(CopyCCRequest request) to support being run from a separate process, using it from inside the IIS instance should not require any changes.
There is a WCF service that is hosted in a .Net Console application. The client creates a duplex channel to the service that has a callback. It calls the service in this way:
var task = Task<object>.Factory.FromAsync(clientRay.Proxy.BeginCalc, clientRay.Proxy.EndCalc, lst_RaySrvcDetails, state);
And here is the Main method of the service Console app:
static void Main(string[] args)
{
ServiceHost srvcHost = new ServiceHost(serviceInstance, uriBase);
//
//Here the service is hosted
//
while(true)
{
;
}
}
And the MyService.cs receives the call in the below method:
public IAsyncResult BeginCalc(List<MBSWaldram.DataAccessLayer.Framework.ServiceDetails> input,
AsyncCallback callback, object state)
{
calcInput = input;
// Create a task to do the work
var task = Task<object>.Factory.StartNew(this.CalcTasks, state);
return task.ContinueWith(res => callback(task));
}
Now the CalcTasks method, where the actual task is run, is showing less performance compare to have it on a WCF Windows Form application. One of the reason I can think of is the way I have used while(true){;} infinite loop so that the application doesn't terminates and waits for the call from the client. Not sure this the best of doing it. For some reason I can't use Windows Form Application.
I appreciate if anyone could shed some light in why there is a performance issue here.
Thanks.
while (true) {;} is really unlucky construction. In Console application take Console.ReadLine() instead. The application will wait until Enter press.
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.