-1

Ok this this works as below

public MainWindow()
{
    CheckCrawlURLs.func_StartCrawlingWaitingUrls();    
}

However this doesn't work below

public MainWindow()
{                 
    Task.Factory.StartNew(() =>
    {
        CheckCrawlURLs.func_StartCrawlingWaitingUrls();
    });
}

The below is the executed class at both examples

public static class CheckCrawlURLs
{
    public static void func_StartCrawlingWaitingUrls()
    {
        PublicStaticFunctions.AddMsgToEvents("Checking waiting crawling urls process started");
        System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
        dispatcherTimer.Tick += new EventHandler(func_CheckWaitingUrls);
        dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
        dispatcherTimer.Start();
    }

    private static void func_CheckWaitingUrls(object sender, EventArgs e)
    {
        PublicStaticFunctions.AddMsgToMoreCommonEvents("Checking waiting to crawl urls...");
        List<string> lstStartCrawling = CrawlURLDB.func_ReturnNextCrawlLinks();
        PublicStaticFunctions.AddMsgToMoreCommonEvents("Number of links to start crawlin: " + lstStartCrawling.Count);
    }
}

So my questions are what is the logic here ?

At second task factory start the func_CheckWaitingUrls is not ticking.

Which one i should use ?

LightBulb
  • 964
  • 1
  • 11
  • 27
Furkan Gözükara
  • 22,964
  • 77
  • 205
  • 342
  • 1
    Just do this the other way around, use the timer to start the task. With some minimum interlocking often needed so you don't start the task again when the previous invocation hasn't finished yet. Or runs when the UI is gone. – Hans Passant Aug 13 '14 at 14:22

1 Answers1

3

As the name suggests, DispatcherTimer is based on the WPF dispatcher. This only works on the GUI thread, obviously.

Have a look at System.Threading.Timer instead - or start just the timer callback on a new thread.

Luaan
  • 62,244
  • 7
  • 97
  • 116
  • ty for answer but more detailed answer would be great – Furkan Gözükara Aug 13 '14 at 14:07
  • @MonsterMMORPG A more detailed answer would depend more on what specifically you're trying to do. For example, it doesn't look like you'd need to start new threads at all - why aren't you using `await`s on asynchronous I/O, combined with e.g. `Task.Delay`? It looks like you're using a DB and doing HTTP requests, both of which are easily done using asynchronous I/O. – Luaan Aug 13 '14 at 14:10
  • I need period checks. So i am starting a function that will do period checks. I want to start this function as a new task. – Furkan Gözükara Aug 13 '14 at 14:14
  • @MonsterMMORPG Right. In that case, create and start the timer in the GUI thread, and start the new task in the `Tick` event handler. It might be useful to make sure the task isn't going to get started if it's already running. – Luaan Aug 13 '14 at 15:31