簡體   English   中英

Windows Phone 8.1應用程序中的后台線程

[英]Background thread in Windows Phone 8.1 app

我正在開發Windows Phone 8.1購物應用程序。 我在應用程序中有一個不斷運行的線程,它下載用戶籃並將其保存在本地緩存中以提高性能。 到目前為止,我所擁有的是這樣的:

while(UserLoggedIn)
{
    await Networking.getBasket();
    await Task.Delay(5000);
}

應用程序恢復時啟動此線程。 我的問題是:控制這樣一個線程的最佳方法是什么? 在應用程序恢復它似乎真的很慢,有時它會阻止UI線程,雖然它是完全異步的。 如何提高性能?

編輯

根據Romasz的建議,我使用了這樣的Timer:

聲明:

Timer _getBasketTimer;

在App的構造函數中初始化它:

_getBasketTimer = new Timer(getBasketCallback, null, 5000, Timeout.Infinite);

定義其回調:

private async void getBasketCallback(Object state)
{
    if (JSONCache.getSessionID() != "" && Networking.LoginInProgress == false)
        await Networking.getBasket();

    //The Change method may be called when the Timer object is already Disposed (I debugged it, and the exception did occur sometimes)
    try
    {
        _getBasketTimer.Change(5000, Timeout.Infinite);
    }
    catch(ObjectDisposedException)
    {

    }
}

將它處理在App的Suspending事件中,因此當應用程序暫停時Thread不會運行:

_getBasketTimer.Dispose();

並在應用恢復時啟動它:

_getBasketTimer = new Timer(getBasketCallback, null, 5000, Timeout.Infinite);

在沒有看到更多代碼的情況下很難分辨,但是您可能需要將循環包裝在新線程中以使其脫離UI線程:

 Task.Run(async () =>
            {
               while(UserLoggedIn)
               {
                  await Networking.getBasket();
                  await Task.Delay(5000);
               }
            });

如果你想在一個線程上間隔運行一些東西(也在UI之外的線程上運行),你可以使用System.Threading.Timer 示例可能如下所示:

System.Threading.Timer myTimer = new System.Threading.Timer(async (state) => { if (UserLoggedIn) await Task.Delay(1000); }, null, 0, 5 * 1000);

請注意,如果您想從計時器的回調中訪問UI元素,則必須使用Dispatcher

另外,一旦應用程序被暫停,請不要忘記停止計時器/取消任務,如果仍需要,請在恢復事件時恢復它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM