标签: task

在不冻结UI的情况下运行长任务

我正在尝试在后台执行操作,而不会冻结UI.

当然,我可以使用BackgroundWorker.

但是,我只想使用Task API.

我试过了:

async void OnTestLoaded(object sender, RoutedEventArgs e)
{
   await LongOperation();
}
// It freezes the UI
Run Code Online (Sandbox Code Playgroud)

和

async void OnTestLoaded(object sender, RoutedEventArgs e)
{
   var task = Task.Run(()=> LongOperation());
   task.Wait();
}


// It freezes the UI
Run Code Online (Sandbox Code Playgroud)

我应该回到BackgroundWorker吗?或者是否只有使用任务的解决方案?

wpf task microsoft-metro

8
推荐指数
1
解决办法
9354
查看次数

TPL中的错误 - TaskContinuationOptions.ExecuteSynchronously?

我想我在TPL中发现了一个严重的错误.我不确定.我花了很多时间挠挠脑袋,无法理解这种行为.有人可以帮忙吗?

我的情景是:

  1. 我创建了一个简单的任务.没有例外等
  2. 我用ExecuteSynchronously set注册了一个延续.它必须在同一个线程上.
  3. 我在默认的taskcheduler(ThreadPool)上启动任务.起始线程继续并等待它.
  4. 任务开始了.通行证.
  5. 继续从与任务相同的线程开始(使前一个任务完成!)并进入无限循环.
  6. 等待线程没有任何反应.不想再往前走.坚持等待.我在调试器中检查过,任务是RunToCompletion.

这是我的代码.感谢任何帮助!

// note: using new Task() and then Start() to avoid race condition dangerous
// with TaskContinuationOptions.ExecuteSynchronously flag set on continuation.

var task = new Task(() => { /* just return */ });
task.ContinueWith(
   _task => { while (true) { } /* never return */ },
   TaskContinuationOptions.ExecuteSynchronously);

task.Start(TaskScheduler.Default);
task.Wait(); // a thread hangs here forever even when EnterEndlessLoop is already called. 
Run Code Online (Sandbox Code Playgroud)

.net task task-parallel-library

8
推荐指数
1
解决办法
1013
查看次数

仅使用异步任务和任务有什么区别?

例如,这段代码之间的区别

public Task<IList<NewsSentimentIndexes>> GetNewsSentimentIndexes(DateTime @from, DateTime to = new DateTime(), string grouping = "1h")
    {
        var result = _conf.BasePath
            .AppendPathSegment("news-sentiment-indexes")
            .SetQueryParams(new
            {
                from = from.ToString("s"),
                to = to.ToString("s"),
                grouping
            });

        return result
           .GetStringAsync()
           .ContinueWith(Desereialize<IList<NewsSentimentIndexes>>);
    }
Run Code Online (Sandbox Code Playgroud)

然后

 public async Task<IList<NewsSentimentIndexes>> GetNewsSentimentIndexes(DateTime @from, DateTime to = new DateTime(), string grouping = "1h")
    {
        var result = _conf.BasePath
            .AppendPathSegment("news-sentiment-indexes")
            .SetQueryParams(new
            {
                from = from.ToString("s"),
                to = to.ToString("s"),
                grouping
            });

        var newsStr =  await result.GetStringAsync();
        return JsonConvert.DeserializeObject<NewsSentimentIndexes>(newsStr);
    }
Run Code Online (Sandbox Code Playgroud)

哪一个正确或更快?只是调用这个方法需要等待或只是一个任务?

c# parallel-processing asynchronous task task-parallel-library

8
推荐指数
2
解决办法
155
查看次数

任务可用的最大线程数

我试图了解C#中的async-await功能.我编写了下面的代码来异步运行几个任务 - 目前他们所做的只是在一段时间后引发一个事件.

public class Program
{
    public static Stopwatch Watch = new Stopwatch();

    public static void Main(string[] args)
    {
        AsyncClass asyncClass = new AsyncClass();
        asyncClass.WaitSecondsAsyncCompleted += asyncClass_WaitSecondsAsyncCompleted;
        List<Task> tasks = new List<Task>();
        Watch.Start();
        for (int i = 1; i < 6; i++)
        {
            tasks.Add(asyncClass.WaitSecondsAsync(i, Watch));
        }
        Task.WaitAll(tasks.ToArray());
        Console.ReadLine();
    }

    private static void asyncClass_WaitSecondsAsyncCompleted(int i)
    {
        Console.WriteLine("{1} : Async Method Called: waited for {0} seconds", i, Watch.ElapsedMilliseconds);
    }
}

public class AsyncClass
{
    public event Action<int> WaitSecondsAsyncCompleted;

    public async Task …
Run Code Online (Sandbox Code Playgroud)

c# multithreading task threadpool async-await

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

c#简单背景线程

我正在寻找一种在后台执行任务的简单方法,然后在完成时更新某些内容(在主线程上).它处于低级"模型"类中,因此我无法调用InvokeOnMainThread,因为我没有NSObject.我有这个方法:

public void GetItemsAsync(Action<Item[]> handleResult)
{
  Item[] items=null;
  Task task=Task.Factory.StartNew(() =>
  {
    items=this.CreateItems(); // May take a second or two
  });
  task.ContinueWith(delegate
  {
    handleResult(items);
  }, TaskScheduler.FromCurrentSynchronizationContext());
}
Run Code Online (Sandbox Code Playgroud)

这似乎工作正常,但是

1)这是最好的(最简单的)方式吗?

2)我担心局部变量:

Item{} items=null
Run Code Online (Sandbox Code Playgroud)

当方法在后台线程完成之前返回时,什么停止消失?

谢谢.

c# multithreading background task

7
推荐指数
1
解决办法
1449
查看次数

什么是python中的C#任务的等价物

我需要将我的c#代码翻译成python.我在c#中有一个Task,需要将它翻译成python.这是一段代码:

List<Task> t = new List<Task>();
for(int i = 0; i < _tasks.Count; i++)
{
     var theTask = _tasks[i];
     t.Add(Task.Factory.StartNew(() => theTask.SAPTask.Execute(theTask.index, theTask.WindowCount)));
}
t.ForEach(x => x.Wait());
Run Code Online (Sandbox Code Playgroud)

这段代码对于运行我的程序至关重要.我需要python在单独的线程中运行列表中的所有任务,并阻止主线程直到所有任务都完成.python有这个功能吗?

c# python task

7
推荐指数
1
解决办法
973
查看次数

在Rust中,如何创建在自己的OS线程中运行的任务?

这个问题已不再适用:锈绿色线程已经消失.所有任务都对应一个线程.

Rust任务在运行时管理的线程池中运行.

我通过将阻止的FFI调用一些代码,我将在紧密的循环中执行它.

如何在自己的OS线程上生成任务?

这两个问题是线程在其线程上保持调度,并且工作窃取调度程序不会在此线程上带来额外的工作.

multithreading task rust

7
推荐指数
1
解决办法
1451
查看次数

错误:返回关键字后面不能跟c #async code中的对象表达式

我在C#中有以下异步代码:

public async Task GetPhotos(List<int> photoIds)
{
    List<Photos> photos = new List<Photos>();

    if (photoIds != null)
    {
        foreach (int photoId in photoIds)
        {
           Photo photo = await ImageRepository.GetAsync(photoId);

           if (photo != null)
              photos.Add(photo);
        }
    }

    return photos;        
}
Run Code Online (Sandbox Code Playgroud)

在return语句中,我收到以下错误消息:

由于GetPhotos(List photoIds)是一个返回'Task'的异步方法,因此return关键字后面不能跟一个对象表达式.你打算退回'任务'吗?

如何解决这个错误?

c# asynchronous task task-parallel-library async-await

7
推荐指数
2
解决办法
7547
查看次数

在UI线程上创建和启动任务

当在工作线程上调用的方法需要在UI线程上运行代码并在执行其他操作之前等待它完成时,可以这样做:

    public int RunOnUi(Func<int> f)
    {
        int res = Application.Current.Dispatcher.Invoke(f);

        return res;
    }
Run Code Online (Sandbox Code Playgroud)

但是,如果我想用任务做什么呢?有没有办法让RunOnUi方法创建一个在UI上启动并返回它的任务,以便调用者(在工作线程上运行)可以等待它?符合以下签名的东西:public Task<int> StartOnUi(Func<int> f)?

一种方法如下:

public Task<int> RunOnUi(Func<int> f)
{
    var task = new Task<int>(f);
    task.Start(_scheduler);

    return task;
}
Run Code Online (Sandbox Code Playgroud)

这里,假设_schduler持有ui TaskScheduler.但是我不太习惯于创建"冷"任务并使用start方法来运行它们.这是"推荐"的方式还是有更优雅的方式来做到这一点?

c# wpf task task-parallel-library

7
推荐指数
1
解决办法
4654
查看次数

在ASP.NET Core上实现"Fire and Forget"方法的安全方法

我正在尝试实现一个简单的日志库,它将用于多个项目.库的工作是将HTTP请求发送到ElasticSearch.这个库的要点是它不能等待响应.另外,我不关心任何错误/异常.它必须将请求发送到ElasticSearch,并立即返回.我不想用返回类型创建接口Task,我希望它们留下来void.

以下是我的示例代码.这是"火与忘"的正确和安全的实施吗?如果我Task.Run()在高负载库中使用它可以吗?或者我应该避免Task.Run()在我的情况下使用?另外,如果我不使用await带Task.Run(),将我阻塞线程?此代码在库中:

public enum LogLevel
{
    Trace = 1,
    Debug = 2,
    Info = 3,
    Warn = 4,
    Error = 5,
    Fatal = 6
}

public interface ILogger
{
    void Info(string action, string message);
}

public class Logger : ILogger
{
    private static readonly HttpClient _httpClient = new HttpClient(new HttpClientHandler { Proxy = null, UseProxy = false });
    private static IConfigurationRoot _configuration;

    public Logger(IConfigurationRoot configuration)
    {
        _configuration = …
Run Code Online (Sandbox Code Playgroud)

c# asynchronous task async-await asp.net-core

7
推荐指数
1
解决办法
2299
查看次数