相关疑难解决方法(0)

正确使用Task.Run时和async-await时

我想问你关于正确架构何时使用的意见Task.Run.我在WPF .NET 4.5应用程序(使用Caliburn Micro框架)中遇到了滞后的UI.

基本上我在做(非常简化的代码片段):

public class PageViewModel : IHandle<SomeMessage>
{
   ...

   public async void Handle(SomeMessage message)
   {
      ShowLoadingAnimation();

      // Makes UI very laggy, but still not dead
      await this.contentLoader.LoadContentAsync();

      HideLoadingAnimation();
   }
}

public class ContentLoader
{
    public async Task LoadContentAsync()
    {
        await DoCpuBoundWorkAsync();
        await DoIoBoundWorkAsync();
        await DoCpuBoundWorkAsync();

        // I am not really sure what all I can consider as CPU bound as slowing down the UI
        await DoSomeOtherWorkAsync();
    }
}
Run Code Online (Sandbox Code Playgroud)

从我阅读/看到的文章/视频中,我知道await async不一定在后台线程上运行,并且需要在后台开始工作,需要等待它Task.Run(async () => …

c# asynchronous task async-await

288
推荐指数
2
解决办法
25万
查看次数

'await'运算符只能与async lambda表达式一起使用

我正在尝试将文件列表复制到目录中.我正在使用async/await.但是我一直在收到这个编译错误

'await'运算符只能在异步lambda表达式中使用.考虑使用'async'修饰符标记此lambda表达式.

这就是我的代码

async Task<int> CopyFilesToFolder(List<string> fileList, 
            IProgress<int> progress, CancellationToken ct)
{
    int totalCount = fileList.Count;
    int processCount = await Task.Run<int>(() =>
    {
        int tempCount = 0;
        foreach (var file in fileList)
        {
            string outputFile = Path.Combine(outputPath, file);

            await CopyFileAsync(file, outputFile); //<-- ERROR: Compilation Error 

            ct.ThrowIfCancellationRequested();
            tempCount++;
            if (progress != null)
            {
                progress.Report((tempCount * 100 / totalCount)));
            }

        }

        return tempCount;
    });
    return processCount;
}


private async Task CopyFileAsync(string sourcePath, string destinationPath)
{
    using (Stream source = File.Open(sourcePath, FileMode.Open))
    { …
Run Code Online (Sandbox Code Playgroud)

c# async-await .net-4.5

13
推荐指数
1
解决办法
3万
查看次数

标签 统计

async-await ×2

c# ×2

.net-4.5 ×1

asynchronous ×1

task ×1