C# Poll() method [duplicate] - c#

This question already has answers here:
How to perform periodic work on an ASP.NET MVC website?
(4 answers)
Closed 7 years ago.
I have created a service class in a MVC 4.5 project. In this class I need to start a Poll method.
What is the best practice in doing this?
This is a mock up, but it needs to be started, and Thread.Sleep is not recommended. And the method should be global, and only one call for each minute.
private void Poll()
{
Foo("Do somethings");
Thread.Sleep(60000);
Poll();
}
Any good suggestions?

Using your approach will eventually result in a StackOverflowException.
You should leverage the built-in Timer class.
You can find the documentation here.
Your usage code would be something like
Timer t = new Timer(o => Foo("Do somethings"), null, 0, 60000);
Side note:
As #RonBeyer pointed out, perhaps polling in an ASP.net might not be the best tool for the job you need to accomplish.
A WCF long-running service for instance with web-hooks to your ASP.Net application would seem appropriate. Again, it depends on what you need to achieve. Don't hesitate to complete your question with more details about what's your ultimate goal.

Related

Create new/Reuse an instance of an application (Windows, .NET, WPF) [duplicate]

This question already has answers here:
What is the correct way to create a single-instance WPF application?
(39 answers)
Closed 6 years ago.
I've been struggling with this for more than several hours and cannot think of a solution.
I have an application that can be started in this way:
TestApplication.exe ID={GUID} filename={filename}
If there is not an instance of the application with the same GUID, a new instance should be started with ID={GUID} and the specified file should be loaded in it.
If there is an instance of the application with the same GUID, the user should be asked if he wants to close the file he is working on and if he confirms it - then the new file specified should be opened in the running instance.
Any ideas how to implement this?
Use a Mutex. See the first answer of this question:
What is the correct way to create a single-instance application?
Any ideas how to implement this?
Yes. Question answered. You never ask us to show us our ideas.
Let's get real.
One way is by window title, but having the GUID there is seriously not optimal.
As such, read up on NAMED MUTEXES. You can use that one to identify a program already running.
Alternatively - and better given you must actually send a signal - named pipes. You can register a named pipe with the GUID. Fails: Already exists. THAT allows the new application to actually signal the old one and or send a shutdown command.

Why ConfigureAwait(false) is not the default option? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
As you know, it it a good idea to call Task.ConfigureAwait(false) when you are waiting on a task in a code that does not need to capture a synchronization context, because it can cause deadlocks otherwise.
Well, how often do you need to capture a synchronization context? I my practice, very rarely. In most situations I am working with "library" code that pretty much forces me to use Task.ConfigureAwait(false) all the time.
So my question is pretty simple: why Task.ConfigureAwait(false) is not the default option for a task? Would not it be much better to force "high-level" code to use Task.ConfigureAwait(true)? Is there a historical reason for it, or am I missing something?
Most code that works with .ConfigureAwait(false) also works, although subobtimal, with .ConfigureAwait(true). Yes, not all code, but still most. The current default lets the highest percentage of code work without tinkering with settings that an average programmer might not understand.
A different default would just lead to thousands of questions about why the code does not work, and worse yet, thousands of answers in the form of "Microsoft sucks, they make you write Control.CheckForIllegalCrossThreadCalls = false; in every program. Why isn't that the default?" rather than actually adding the appropriate .ConfigureAwait(true) calls.
Look at the second example solution from that link:
public async void Button1_Click(...)
{
var json = await GetJsonAsync(...);
textBox1.Text = json;
}
public class MyController : ApiController
{
public async Task<string> Get()
{
var json = await GetJsonAsync(...);
return json.ToString();
}
}
If the default behaviour was ConfigureAwait(false), the textBox1.Text = json; statement would execute on a random thread pool thread instead of the UI thread.
Both snippets look like code someone could reasonably write, and by default one of them has to be broken. Since deadlocks are a lot less dangerous and easier to detect than thread-unsafe accesses, picking ConfigureAwait(true) as the default is the more conservative choice.
Just because your typical use case requires ConfigureAwait(false), it doesn't mean that it is the "correct" or most used option.
One of the things async/await is designed for, is to write responsive GUI programs. In such cases, returning to the UI thread after offloading some work to a Task is critical, since UI updates can only happen from the main thread on most Windows GUI platforms. Async/await helps GUI developers do the right thing.
This is not the only example where the default option makes better sense. I can only speculate, but I would suspect that the decision for the ConfigureAwait default is based on making sure async works with as little friction as possible, for the use cases that Microsoft anticipates it will be used for the most. Not everyone writes frameworks.

Using static functions in a asp.net 3.5 website [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am building a ASP.NET webapplication in which I use several classes containing static functions for retreiving database values and such (based on session of user so their results are session specific, not application wide).
These functions can also be called from markup, which makes developing my GUI fast and easy.
Now I am wondering: is this the right way of doing things, or is it better to create a class, containing these functions and create an instance of the class when needed?
What will happen when there are a lot of visitors to this website? Will a visitor have to wait until the function is 'ready' if it's also called by another session? Or will IIS spread the workload over multiple threads?
Or is this just up to personal preferences and one should test what works best?
EDIT AND ADDITIONAL QUESTION:
I'm using code like this:
public class HandyAdminStuff
{
public static string GetClientName(Guid clientId)
{
Client client = new ClientController().GetClientById(clientId);
return client.Name;
}
}
Will the Client and ClientController classes be disposed of after completion of this function? Will the GarbageCollector dispose of them? Or will they continue to 'live' and bulk up memory everytime the function is called?
** Please, I don't need answers like: 'measure instead of asking', I know that. I'd like to get feedback from people who can give a good answer an maybe some pro's or cons, based on their experience. Thank you.
"Will a visitor have to wait until the function is 'ready' if it's also called by another session?"
Yes. It may happen if you have thread safe function body, or you perform some DB operations within transaction that locks DB.
Take a look at these threads:
http://forums.asp.net/t/1933971.aspx?THEORY%20High%20load%20on%20static%20methods%20How%20does%20net%20handle%20this%20situation%20
Does IIS give each connected user a thread?
It would be better to have instance based objects because they can also be easily disposed (connections possibly?) and you wouldn't have to worry about multithreading issues, additional to all the problems "peek" mentioned.
For example, each and every function of your static DAL layer should be atomic. That is, no variables should be shared between calls inside the dal. It is a common mistake in asp.net to think that [TreadStatic] data is safe to be used inside static functions. The only safe pool for storing per request data is the Context.Items pool, everything else is unsafe.
Edit:
I forgot to answer you question regarding IIS threads. Each and every request from your customers will be handled by a different thread. As long as you are not using Session State, concurrent requests from the same user will be also handled concurrently by different threads.
I would not recommend to use static function for retrieving data. This because these static functions will make your code harder to test, harder to maintain, and can't take advantage of any oo principals for design. You will end up with more duplicate code, etc.

Run System.Timers.Timer event on specific day and time each week c# [duplicate]

This question already has answers here:
How to call a method daily, at specific time, in C#?
(19 answers)
Closed 9 years ago.
I'm in the process of writing a windows service using System.Timers.Timer to keep track of my interval. What I'd like to do is make it so my service will launch on a specific day and time based on variables in my app.config file.
I don't think you're really writing a Windows service, I think you're writing a job. A cleaner, and easier approach, to your problem would be to write a Console application and then setup a Windows Scheduled Task to run that Console application at the intervals you want.
Never mind the fact that you'll have to set the time in milliseconds with the Timer approach, the Windows service would not be capable of handling Daylight Savings Time and more.
Although I think your best bet is to make this a scheduled task, you can easily create a waitable timer that will signal at the same time every day. Windows has a Waitable Timer object, but there's no .NET support for it.
I published an article a while back called Waitable Timers in C#, in which I showed how to use this object from a C# program. Unfortunately, the site that published the article is no longer. However, you can download the code examples for the article from my site at http://www.mischel.com/pubs/waitabletimer.zip. You're free to use the code in any way you see fit.

Run C# code at specific time [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C# Execute function at specific time
I want to run certain function at certain time.I tried Timer control.it's not working. My question is:How can I run a function every day at the 19:00 in C#?
Is there any way to check the time and have a Timer object?
Timer code:
int Interval(TimeSpan gorevZamani)
{
if ((gorevZamani - DateTime.Now.TimeOfDay).TotalMilliseconds > 0.0)
return (int)(gorevZamani - DateTime.Now.TimeOfDay).TotalMilliseconds;
else
return (int)((gorevZamani - DateTime.Now.TimeOfDay).Add(TimeSpan.FromDays(1)).TotalMilliseconds);
}
in the question set as possible duplicate: C# Execute function at specific time people suggest to use either Quartz.NET or windows Task Scheduler.
Both options could eventually serve the purpose but I believe, as I suggested already few times in similar previous questions, Windows Task Scheduler is better because you no code anything for it and let Windows do the scheduling for you and you focus only on the real business case of your application, which is what Windows cannot do for you, then rely on existing technologies to glue things together and don't have to debug or reinvent what has been done and is available for you anyway.
Use a scheduled task. A good way to do this is the at command, documented on MSDN here.

Categories