我正在尝试在后台执行操作,而不会冻结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吗?或者是否只有使用任务的解决方案?
我想我在TPL中发现了一个严重的错误.我不确定.我花了很多时间挠挠脑袋,无法理解这种行为.有人可以帮忙吗?
我的情景是:
这是我的代码.感谢任何帮助!
// 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) 例如,这段代码之间的区别
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
我试图了解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) 我正在寻找一种在后台执行任务的简单方法,然后在完成时更新某些内容(在主线程上).它处于低级"模型"类中,因此我无法调用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#代码翻译成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有这个功能吗?
这个问题已不再适用:锈绿色线程已经消失.所有任务都对应一个线程.
Rust任务在运行时管理的线程池中运行.
我通过将阻止的FFI调用一些代码,我将在紧密的循环中执行它.
如何在自己的OS线程上生成任务?
这两个问题是线程在其线程上保持调度,并且工作窃取调度程序不会在此线程上带来额外的工作.
我在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关键字后面不能跟一个对象表达式.你打算退回'任务'吗?
如何解决这个错误?
当在工作线程上调用的方法需要在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方法来运行它们.这是"推荐"的方式还是有更优雅的方式来做到这一点?
我正在尝试实现一个简单的日志库,它将用于多个项目.库的工作是将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) task ×10
c# ×7
async-await ×3
asynchronous ×3
wpf ×2
.net ×1
asp.net-core ×1
background ×1
python ×1
rust ×1
threadpool ×1