2013-02-19 15 views
6

मैं सी # और xaml का उपयोग कर एक विंडोज स्टोर ऐप बना रहा हूं। मुझे समय के कुछ अंतराल के बाद डेटा को रीफ्रेश करने की आवश्यकता है (सर्वर से नया डेटा लाएं)।फ़ंक्शन के कार्यकाल को पूरा करने के बाद समय-समय पर फ़ंक्शन निष्पादित करना

TimeSpan period = TimeSpan.FromMinutes(15); 
    ThreadPoolTimer PeriodicTimer =  ThreadPoolTimer.CreatePeriodicTimer(async(source)=> { 
    n++; 
    Debug.WriteLine("hello" + n); 
    await dp.RefreshAsync(); //Function to refresh the data 
    await Dispatcher.RunAsync(CoreDispatcherPriority.High, 
       () => 
       { 
        bv.Text = "timer thread" + n; 

       }); 

     }, period); 

यह ठीक से काम कर रहा है: मैं समय-समय पर मेरी ताज़ा समारोह निष्पादित करने के लिए इस प्रकार ThreadPoolTimer इस्तेमाल किया। एकमात्र समस्या यह है कि अगर रीफ्रेश फ़ंक्शन थ्रेड पूल में सबमिट होने से पहले पूरा नहीं होता है। क्या इसके निष्पादन के बीच अंतर निर्दिष्ट करने का कोई तरीका है।

चरण 1: ताज़ा फ़ंक्शन निष्पादित

चरण 2 (समय की किसी भी राशि लेता है): ताज़ा समारोह पूरा करता है इसके निष्पादन

चरण 3: 15 मि के लिए गैप तो चरण 1

ताज़ा समारोह जाना निष्पादित करता है। इसके निष्पादन समाप्त होने के बाद 15 मिनट, यह फिर से निष्पादित करता है।

उत्तर

6

AutoResetEvent इस समस्या को हल करेगा। एक वर्ग-स्तर AutoResetEvent उदाहरण घोषित करें।

AutoResetEvent _refreshWaiter = new AutoResetEvent(true); 

फिर अपने कोड के अंदर: 1. इस पर इंतजार जब तक यह संकेत है, और 2. RefreshAsync विधि के लिए एक तर्क के रूप में अपनी संदर्भ गुजरती हैं।

TimeSpan period = TimeSpan.FromMinutes(15); 
    ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer(async(source)=> { 
    // 1. wait till signaled. execution will block here till _refreshWaiter.Set() is called. 
    _refreshWaiter.WaitOne(); 
    n++; 
    Debug.WriteLine("hello" + n); 
    // 2. pass _refreshWaiter reference as an argument 
    await dp.RefreshAsync(_refreshWaiter); //Function to refresh the data 
    await Dispatcher.RunAsync(CoreDispatcherPriority.High, 
       () => 
       { 
        bv.Text = "timer thread" + n; 

       }); 

     }, period); 

अंत में, dp.RefreshAsync विधि के अंत में है, तो फोन _refreshWaiter.Set(); है कि अगर 15 सेकंड तो बीत चुके हैं अगले RefreshAsync बुलाया जा सकता है। ध्यान दें कि यदि RefreshAsync विधि 15 मिनट से कम समय लेती है, तो निष्पादन सामान्य के रूप में आता है।

4

मुझे लगता है कि यह करने के लिए एक आसान तरीका async साथ है:

private async Task PeriodicallyRefreshDataAsync(TimeSpan period) 
{ 
    while (true) 
    { 
    n++; 
    Debug.WriteLine("hello" + n); 
    await dp.RefreshAsync(); //Function to refresh the data 
    bv.Text = "timer thread" + n; 
    await Task.Delay(period); 
    } 
} 

TimeSpan period = TimeSpan.FromMinutes(15); 
Task refreshTask = PeriodicallyRefreshDataAsync(period); 

यह समाधान भी एक Task जो त्रुटियों का पता लगाने के लिए इस्तेमाल किया जा सकता है।

संबंधित मुद्दे

 संबंधित मुद्दे