logo
down
shadow

C# background worker and timer loop


C# background worker and timer loop

By : user3862189
Date : November 22 2020, 07:01 PM
it fixes the issue Your error is caused by you setting the Timer to null, to solve that just remove my_timer = null; (2x).
But a Timer is not well suited for 'pausing' a Thread (BGW). A simple solution looks like:
code :


Share : facebook icon twitter icon
using timer in background worker in windows phone

using timer in background worker in windows phone


By : sigognac
Date : March 29 2020, 07:55 AM
wish help you to fix your issue What you're planning to do wont work.
Both your _Timer1_Tick and _Timer2_Tick will run in the UI thread. If you perform some long-running operations there, it'll hang the UI.
WPF multitasking along with a timer and background worker

WPF multitasking along with a timer and background worker


By : Esprit Solutions Pvt
Date : March 29 2020, 07:55 AM
help you fix your problem It looks to me as though you don't even need the BackgroundWorker. Currently you have:
code :
private void timer_Elapsed(object sender, EventArgs e)
{
    TimerObject.Stop();

    BackgroundWorker backgroundWorkerObject = new BackgroundWorker();
    backgroundWorkerObject.DoWork += new DoWorkEventHandler(StartThreads);
    backgroundWorkerObject.RunWorkerAsync();

    TimerObject.Start();
}


private void StartThreads(object sender, DoWorkEventArgs e)
{
    tasks = new Task[4];
    tasks[0] = Task.Factory.StartNew(() => DoSomeLongWork());
    tasks[1] = Task.Factory.StartNew(() => DoSomeLongWork());
    tasks[2] = Task.Factory.StartNew(() => DoSomeLongWork());
    tasks[3] = Task.Factory.StartNew(() => DoSomeLongWork());

    // Give the tasks a second to start.
    Thread.Sleep(1000);
}
private void timer_Elapsed(object sender, EventArgs e)
{
    TimerObject.Stop();

    tasks = new Task[4];
    tasks[0] = Task.Factory.StartNew(() => DoSomeLongWork());
    tasks[1] = Task.Factory.StartNew(() => DoSomeLongWork());
    tasks[2] = Task.Factory.StartNew(() => DoSomeLongWork());
    tasks[3] = Task.Factory.StartNew(() => DoSomeLongWork());

    TimerObject.Start();
}
int localIndex;
// lock the global variable from accessing by multiple threads at a time
lock (_countLock)
{
    localIndex = Index;
    Index++;
}
localIndex = Interlocked.Increment(ref Index, 1) - 1;
Timer vs. repetitive background worker

Timer vs. repetitive background worker


By : shunxie321
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further A Timer is almost certainly more suitable in terms of resource consumption. A BackgroundWorker is going to create a new thread just for that task. Creating a new thread is a fairly expensive operation. While there are many different timer implementations, and their implementations will vary, they are generally going to be reliant on OS tools that will fire an event periodically, which is going to be preferable to starting up a new dedicated thread.
Most of the key differences in Timer objects is what they do when they're "ready". Some create a new thread pool thread; some have a dedicated thread that is shared by all instances of the timer to run the handler(s), some marshal the code to the UI thread (or some other synchronization context) and it's the latter that you probably want. If you use the timer that is made available in the particular UI framework that you're using it's the behavior that you'll see.
Data acquisition loop using timer / task / background worker

Data acquisition loop using timer / task / background worker


By : julioog
Date : March 29 2020, 07:55 AM
will be helpful for those in need So if I understand it correctly you want to run some code at every 250ms. Even if the code takes 40ms, waiting for 250ms using a Thread.Sleep(250) is not desired because in total it will take 290ms.
You could use a Timer or use something like this:
code :
const int MaxAllowTimeInMs = 250;

async Task Main()
{
    while(true)
    {
        var cts = new CancellationTokenSource();
        cts.CancelAfter(MaxAllowTimeInMs);

        try
        {           
            await Task.WhenAll(new[] 
            { 
                MyTask(cts.Token), 
                Task.Delay(MaxAllowTimeInMs) 
            });
        }
        catch (OperationCanceledException)
        {
            // MyTask took longer than 250ms 
        }
    }
}

async Task MyTask(CancellationToken ct)
{
    // Get some data
    ...

    ct.ThrowIfCancellationRequested(); 

    // If you reach this point, you can process stuff knowing that it took less than 250ms to get it.
}
const int MaxAllowTimeInMs = 250;

void Main()
{
    var timer = new  DispatcherTimer();
    timer.Interval = TimeSpan.FromMilliseconds(MaxAllowTimeInMs);
    timer.Tick += async (s, e) =>
    {
        using(var cts = new CancellationTokenSource())
        {
            try
            {
                cts.CancelAfter(MaxAllowTimeInMs);
                await MyTask(cts.Token);
            }
            catch (OperationCanceledException)
            {
                // MyTask took longer than 205ms
            }
        }
    };
    timer.Start();
}

async Task MyTask(CancellationToken ct)
{
    // Simulate some work
    ...
    ct.ThrowIfCancellationRequested();
}
Are there better ways for updating an execution timer every second than using a background worker that checks every 150

Are there better ways for updating an execution timer every second than using a background worker that checks every 150


By : user300193
Date : March 29 2020, 07:55 AM
may help you . I have found that if you want to display changes every second then you should attempt to make the changes every tenth of a second for it to appear continuous for the user - maybe even more often than that.
Now I would avoid the use of a background worker entirely for this. Instead I'd use Microsoft's Reactive Framework (NuGet "Rx-Main" or "Rx-WinForms" in your case).
Related Posts Related Posts :
  • How to use Selenium Grid with C#?
  • What is the best way to download files via HTTP using .NET?
  • How to get files from a device using USB
  • Given a user's SID, how do I get their userPrincipalName?
  • NHibernate mapping in Asp.Net using MySql
  • Why do some cookies have a '.' before the domain?
  • C# SqlDataReader = null?
  • InvalidCastException for two Objects of the same type
  • "The parameters dictionary contains a null entry for parameter" - How to fix?
  • Font family name from font file
  • What is the best way to generate KML files in C#?
  • How can I receive mail using .NET?
  • How to send raw data over a network?
  • meaning of '+='
  • Object reference not set to an instance of an object #5
  • C# Create "wireframe"/3D "map"
  • How to change size of database
  • Serialization problem
  • Using unmanaged code from managed code
  • Are there any bindings between .NET and TK
  • error with linq join
  • VB.NET equivalent to C# var keyword
  • Accessing object properties from string representations
  • Inheritance issue
  • C# timer won't tick
  • How to retrieve items from a database c#
  • Sending mail using SmtpClient in .net
  • Tag problem c# listbox
  • How to know if the Form App open or not c#
  • C# XPath id() not working?
  • Load PDF from Memory ASP.Net
  • C# ListView with a ProgressBar
  • Getting the right WPF dispatcher in a thread
  • How to create Pivot table using C#?
  • how to download a file from remote server using asp.net
  • Binding files in C#?
  • Copy one object to another
  • How to post on Google Buzz?
  • Generic <T> how cast?
  • Set global hotkeys using C#
  • Change the key being pressed with C#
  • Uploading Large Files
  • How do I get the duration of a video file using C#?
  • how to create instance for a generic type in c#
  • Drag and drop rectangle in C#
  • RSA Encryption C#
  • Title=
  • What is meant by Web Services?
  • The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via
  • Check if server exists
  • time interval in c#
  • Extracting a sub-string in C#
  • C# - Programmatically Log-off and Log-on a user
  • c# array vs generic list
  • TCPClient in C# (Error)
  • How can I know if a file has been changed in .NET C#?
  • New to C# and trying to use a global variable
  • Convert RGB color to CMYK?
  • Tesseract.NET in C#
  • Is it possible to Update Sharepoint List Without "ID"?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk