【发布时间】:2015-02-20 04:39:04
【问题描述】:
我正在为 Windows 应用商店创建幻灯片应用。我想在图片之间暂停 3 秒。
await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(3));
以上代码对我来说工作正常,但线程在大约 30 秒后完成,代码为 0。 我知道 0 表示成功,但上面的代码在一个永久循环中(如果最后达到 pic 索引,则从开始重置索引,就像 Windows Photoviewer 一样)
如何实现所需的功能?
更新:这里是代码
private async void slideshow()
{
while (current_pic_index < fileList.Count)
{
if (current_pic_index < 0)
{
current_pic_index = fileList.Count - 1;
}
IRandomAccessStream fileStream = await fileList[current_pic_index].OpenAsync(Windows.Storage.FileAccessMode.Read);
BitmapImage bi3 = new BitmapImage();
bi3.SetSource(fileStream);
ImageBrush myBrush = new ImageBrush();
Grid DynamicGrid = new Grid();
ContentRoot.Children.Add(DynamicGrid);
DynamicGrid.Width = Window.Current.Bounds.Width;
DynamicGrid.Height = Window.Current.Bounds.Height;
DynamicGrid.HorizontalAlignment = HorizontalAlignment.Right;
DynamicGrid.VerticalAlignment = VerticalAlignment.Bottom;
DynamicGrid.Background = myBrush;
DynamicGrid.ManipulationMode = ManipulationModes.TranslateX;
DynamicGrid.ManipulationStarted += test_grid_ManipulationStarted;
DynamicGrid.ManipulationCompleted += test_grid_ManipulationCompleted;
await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(3));
current_pic_index++;
if(current_pic_index == fileList.Count)
{
current_pic_index = 0;
}
}
}
【问题讨论】:
-
你知道为什么即使循环无限,线程也能在30秒内运行完成吗?
-
Task.Delay仅返回Task,而不是Task<int>。目前尚不清楚“使用代码 0 完成......”是什么意思。你能澄清一下吗?另外,请考虑共享循环代码。 -
@kennyzx 不,我不明白。首先我想可能是因为一些无效的索引。但它是30秒。假设如果我添加 5 张图片然后循环继续两次。但后来我又添加了 3 张图片,然后循环运行了 1 次半,这意味着第一轮完成,然后在第二轮中间中断。
-
@c45207 我是这个领域的新手。我正在尝试从 stackoverflow 中学习。我有一个名为 slideshow() 的函数。我只想让一切暂停 3 秒。你能告诉我怎么做吗?
-
这行代码没有问题,你需要展示剩下的代码——slideshow()和while循环。
标签: multithreading windows-store-apps async-await thread-sleep