Skip to main content
 首页 » 编程设计

c#之如何将Dispatcher或Task的值传递给外部

2024年02月20日10dflying

谁能帮我在任务之间传递变量?

关于 Dispatcher.RunAsync(),我遇到了麻烦。我将变量 RssItem 声明为 RSSItem 的类型。 我正在尝试将 Dispatcher.RunAsync(...) 内部的 await m_RSSReader.CreateRSSItem() 返回的 RssItem 值传递到外部以进行分配 m_RssItemList.Add(RssItem);。

RSSItem RssItem; 
// Save Individual RSS items as RSSItem 
foreach (SyndicationItem item in CurrentFeed.Items) 
{ 
    //RssItem = new RSSItem(); 
    // by using dispatcher, it resolves the issue of lagging UI 
    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => 
        { 
            RssItem = await m_RSSReader.CreateRSSItem(item.Links[0].Uri, m_CurrentRSSDataGroup, item, CurrentFeed); 
        }); 
 
        if (RssItem != null) 
        { 
            Debug.WriteLine("RssItem Title : {0}", RssItem.Title); 
            m_RssItemList.Add(RssItem); 
        } 
} 

[7/11/12] RSSItem 是我创建的用于存储的类。我使用 Dispatcher.RunAsync() 来避免 UI 中断,方法 m_RSSReader.CreateRSSItem() 将返回我想要的类 (RSSItem RssItem)。但我需要将它传递到 Dispatcher 任务之外并将 RssItem 添加到列表 (m_RssItemList.Add(RssItem)。但是我无法将 RssItem 传递到 Dispatcher 之外。

谢谢,

请您参考如下方法:

我不知道您是否使用 Task.Run 解决了它,但是如果您确实想要等待 dispatcher.RunAsync,您还可以使用 WaitHandle,例如 ManualResetEvent。出于某种原因,RunAsync 调用会继续进行,但实际上并未“等待”。 waithandle 会处理这个问题。

// assign to null, since it will be "unassigned" otherwise 
RssItem rssItem = null; 
EventWaitHandle waithandle = new ManualResetEvent(false); 
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => 
{ 
    rssItem = await m_RSSReader.CreateRSSItem(item.Links[0].Uri, m_CurrentRSSDataGroup, item, CurrentFeed); 
    waithandle.Set(); 
}); 
 
waithandle.WaitOne(); 
if (rssItem != null) 
{ 
    Debug.WriteLine("RssItem Title : {0}", rssItem.Title); 
    m_RssItemList.Add(rssItem); 
}