我希望我的AsyncTask班级TextView从布局中更改a的可见性,但出现致命错误。如果我想获取的文本值TextView,它可以正常工作,但是在尝试设置可见性时会崩溃。
// Main Activity (MainActivity.java)
Context MainContext= getApplicationContext();
new MyAsyncTask((TextView)findViewById(R.id.my_text_view)).execute();
// My Async Task (MyAsyncTask.java)
public class MyAsyncTask extends AsyncTask <String, Void, String> {
private Context context;
private TextView my_text_view;
public MyAsyncTask (TextView my_text_view){
this.context = MainActivity.MainContext;
this.txt_loading = my_text_view;
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
my_text_view.setVisibility(View.VISIBLE); // crashes
Log.i("Value: ", String.valueOf(this.my_text_view.getText())); // O.K.!
return null;
}
@Override
protected void onPostExecute(String result) {
}
@Override
protected void onPreExecute() …Run Code Online (Sandbox Code Playgroud) 我开始玩任务和异步等待.为了更好地处理如何转换现有代码,我想我会尝试更改同步运行的当前方法:
private bool PutFile(FileStream source, string destRemoteFilename, bool overwrite)
{
if (string.IsNullOrEmpty(destRemoteFilename)) return false;
string path = Path.GetDirectoryName(destRemoteFilename);
if (path == null) return false;
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
if (overwrite)
{
if (File.Exists(destRemoteFilename)) //delete file if it exists, because we are going to write a new one File.Delete(destRemoteFilename);
}
else if (File.Exists(destRemoteFilename)) return false;
using (FileStream dest = File.OpenWrite(destRemoteFilename))
{
source.Seek(0, SeekOrigin.Begin);
source.CopyTo(dest);
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
我试图简单地改变方法async,并且涉及Task<bool>但我显然在这里遗漏了一些东西,因为它们似乎都不起作用.我经历过的Type System.Threading.Task<bool>是不值得期待的.
我可以在onBackPressed()方法的帮助下删除app.我是通过以下方法做到的:
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
QuestionListActivity.this.finish();
}
Run Code Online (Sandbox Code Playgroud)
但该应用程序仍然在多任务栏的单元格/选项卡中的实例.我想删除它.请建议..
我有接收文件列表的功能,并在单个/单独的线程中工作:
public void DoWork(params...)
{
_filesInProcess = 0;
_filesFinished = 0;
_tokenSource = new CancellationTokenSource();
var token = _tokenSource.Token;
Task.Factory.StartNew(() =>
{
try
{
Parallel.ForEach(_indexedSource,
new ParallelOptions
{
MaxDegreeOfParallelism = parallelThreads //limit number of parallel threads
},
file =>
{
if (token.IsCancellationRequested)
return;
//do work...
});
}
catch (Exception)
{ }
}, _tokenSource.Token).ContinueWith(
t =>
{
//finish...
if (OnFinishWorkEventHandler != null)
OnFinishWorkEventHandler(this, EventArgs.Empty);
}
, TaskScheduler.FromCurrentSynchronizationContext() //to ContinueWith (update UI) from UI thread
);
}
Run Code Online (Sandbox Code Playgroud)
我添加了在循环中运行此命令的选项,在此函数完成后从主窗体运行,如果我需要另一个循环,我再次调用此函数,但在第二次冻结我的所有UI,我无法找到原因
这就是我调用我的函数的方式:
private void StartJob() …Run Code Online (Sandbox Code Playgroud) Result正如Stephen Cleary关于该主题的文章所示,访问任务的属性有可能阻止任务完成.
我想Result在已完成的任务上访问将永远不会阻止,但我找不到任何确认这一点的来源.是这样吗?
我创建了已定义的2个任务类型,并在主程序中实例化它们.
如何在单独的任务之间发送会合?
Procedure Task_Prog is
task type Task_one is
entry Redezvous_One;
end Task_one;
task type Task_Two is
entry Redezvous_Two;
end Task_Two;
task body Task_one is
Finished : Boolean := False;
begin
while not Finished loop
accept Redezvous_One do
finished := True;
Task_Instantiation_B.Redezvous_Two;
end Redezvous_One;
end loop;
end Task_one;
task body Task_Two is
Finished : Boolean := False;
begin
while not Finished loop
accept Redezvous_Two do
finished := True;
end Redezvous_Two;
end loop;
end Task_Two;
Task_Instantiation_A : Task_one;
Task_Instantiation_B: Task_Two;
begin …Run Code Online (Sandbox Code Playgroud) 我正在尝试将旧项目从BackgroundWorker转换为异步/等待,但我真的很难让进度条更新.我遵循了这篇文章但却无法像以下一样工作:
这是我的代码:
private async void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
pb.Show();
btnCancel.Enabled = true;
var progressIndicator = new Progress<int>(ReportProgress);
List<string> updates = Directory.GetFiles(txtInput.Text).ToList();
try
{
await ProcessUpdates(updates, progressIndicator, _cts.Token);
}
catch (OperationCanceledException ex)
{
MessageBox.Show(ex.Message, "Operation Cancelled");
}
btnStart.Enabled = true;
pb.Hide();
btnCancel.Enabled = false;
}
async Task<int> ProcessUpdates(List<string> updatePaths, IProgress<int> progress, CancellationToken ct)
{
int total = updatePaths.Count;
for (int i = 0; i < updatePaths.Count; i++)
{
ct.ThrowIfCancellationRequested();
string update = updatePaths[i];
ssFile.Text = …Run Code Online (Sandbox Code Playgroud) 我在掌握任务和取消令牌方面遇到了一些问题.我做了一个看起来像这样的程序:
static void Main(string[] args)
{
CancellationTokenSource token = new CancellationTokenSource();
Stopwatch stop = new Stopwatch();
stop.Start();
for (int i = 0; i < 5; i++)
{
//Thread.Sleep(1000);
Task.Factory.StartNew(() => myLongTask(token.Token, (i + 1) * 1000));
}
while (true)
{
Thread.SpinWait(1000);
if (stop.ElapsedMilliseconds > 3000)
{
token.Cancel();
}
}
}
public static void myLongTask(CancellationToken token, int time)
{
if (token.IsCancellationRequested)
{
Console.WriteLine("Cancelled");
return;
}
var sw = Stopwatch.StartNew();
Console.WriteLine($"Task {time / 1000} started");
while (sw.ElapsedMilliseconds < time)
Thread.SpinWait(1000);
Console.WriteLine($"Task {time …Run Code Online (Sandbox Code Playgroud) 为什么以下程序只运行有限数量的被阻止任务.限制数似乎是机器上的核心数.
最初,当我写这篇文章时,我希望看到以下内容:
然而输出是:
当在具有32个内核的服务器上运行时,程序确实按照我的预期运行.
class Program
{
private static object _lock = new object();
static void Main(string[] args)
{
int completeJobs = 1;
var limiter = new MyThreadLimiter();
for (int iii = 1; iii < 100000000; iii++)
{
var jobId = iii;
limiter.Schedule()
.ContinueWith(t =>
{
lock (_lock)
{
completeJobs++;
Console.WriteLine("Job: " + completeJobs + " scheduled");
}
});
}
Console.ReadLine();
}
}
class MyThreadLimiter
{
readonly SemaphoreSlim _semaphore …Run Code Online (Sandbox Code Playgroud) 我正在努力了解这个简单程序中正在发生的事情。
在下面的示例中,我有一个任务工厂,该工厂使用ParallelExtensionsExtras中的LimitedConcurrencyLevelTaskScheduler,并将maxDegreeOfParallelism设置为2。
然后,我启动2个任务,每个任务都调用一个异步方法(例如,一个异步Http请求),然后获取等待者和已完成任务的结果。
问题似乎是Task.Delay(2000)永远无法完成。如果我将maxDegreeOfParallelism设置为3(或更大),它将完成。但是在maxDegreeOfParallelism = 2(或更小)的情况下,我的猜测是没有可用的线程来完成任务。这是为什么?
它似乎与async / await有关,因为如果我删除它并简单地Task.Delay(2000).GetAwaiter().GetResult()在DoWork它中运行就完美了。异步/等待是以某种方式使用父任务的任务计划程序,或者它是如何连接的?
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Threading.Tasks.Schedulers;
namespace LimitedConcurrency
{
class Program
{
static void Main(string[] args)
{
var test = new TaskSchedulerTest();
test.Run();
}
}
class TaskSchedulerTest
{
public void Run()
{
var scheduler = new LimitedConcurrencyLevelTaskScheduler(2);
var taskFactory = new TaskFactory(scheduler);
var tasks = Enumerable.Range(1, 2).Select(id => taskFactory.StartNew(() => DoWork(id)));
Task.WaitAll(tasks.ToArray());
}
private void DoWork(int id)
{
Console.WriteLine($"Starting Work {id}");
HttpClientGetAsync().GetAwaiter().GetResult();
Console.WriteLine($"Finished …Run Code Online (Sandbox Code Playgroud)