在传递TaskScheduler.FromCurrentSynchronizationContext作为第二个参数时,Task.ContinueWith中的编译错误

时间:2018-01-31 16:46:19

标签: task

private  void CountWithTask_Click(object sender, RoutedEventArgs e)
{
   lblOutput.Content = "file is in processing...";
   var taskInt = CountWords();
   taskInt.ContinueWith(x => 
   {
      MessageBox.Show("process has been done.");
      lblOutput.Content = $"count of words in file are :- {x.Result}";
      },TaskScheduler.FromCurrentSynchronizationContext);
   }
}

在我返回“x.Result”的代码片段中,我在那时得到了编译错误。错误是image 1 “任务不包含'结果'的定义,并且没有扩展方法'结果'可以找到'任务'类型的第一个参数(你是否缺少使用指令或汇编参考?)”

如果我删除该行,那么它在TaskScheduler上发出错误,错误是 “参数2:无法从'method-group'转换为Cacellationtoken。” enter image description here

CountWords方法的代码:

public async Task<int> CountWords()
        {
            Debug.WriteLine(string.Format($"Thread ID: {Thread.CurrentThread.ManagedThreadId.ToString()}"));
            await Task.Delay(2000);
            int count;
            StreamReader reader = new StreamReader(FileName);           
            var str = await reader.ReadToEndAsync();
            count = str.Length;
            reader.Close();

            return count;
        }

1 个答案:

答案 0 :(得分:0)

我遇到了问题,这个问题非常小,我的错误和我对情报的疏忽。 :)      我只使用“TaskScheduler.FromCurrentSynchronizationContext”,这是错误的,因为“FromCurrentSynchronizationContext”是一个方法,它应该像这样“TaskScheduler.FromCurrentSynchronizationContext()”。

正确的代码是:

private  void CountWithTask_Click(object sender, RoutedEventArgs e)
{
   lblOutput.Content = "file is in processing...";
   var taskInt = CountWords();
   taskInt.ContinueWith(x => 
   {
      MessageBox.Show("process has been done.");
      lblOutput.Content = $"count of words in file are :- {x.Result}";
      },TaskScheduler.FromCurrentSynchronizationContext());
   }
}

感谢@scott的回复。

感谢Stackoverflow。 :)