我正在尝试使用该参考.我知道它在c#4中.我不知道我现在有什么.
但基本上,当我写这行时:
Task.Factory.StartNew(someMethod);
Run Code Online (Sandbox Code Playgroud)
它告诉我这是一个错误.有没有办法解决它,所以我的ide将识别该库(任务并行库)?
该想法:创建Task,打印星号的越来越多.当用户按下时Enter,Task打印件10用星号表示然后停止.
该代码:
namespace CancellingLongRunningTasks
{
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main()
{
var cancellationTokenSource = new CancellationTokenSource();
var token = cancellationTokenSource.Token;
Task task = Task.Run(() =>
{
int count = 1;
while (!token.IsCancellationRequested)
{
Console.WriteLine(new string('*', count));
Thread.Sleep(1000);
count++;
}
}, token).ContinueWith(
parent =>
{
var count = 10;
while (count > 0)
{
Console.WriteLine(new string('*', count));
Thread.Sleep(1000);
count--;
}
}, TaskContinuationOptions.OnlyOnCanceled);
Console.WriteLine("Press enter …Run Code Online (Sandbox Code Playgroud) 我试图掌握.NET中的多线程编程.
我想在for循环中创建100个任务,每个任务将睡眠1秒然后输出它创建的i和它的托管线程ID.完成所有任务后,我想输出经过的总时间.
所以我正在运行这个简单的代码
private static void Main(string[] args)
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < 100; i++)
{
tasks.Add(Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);
Console.WriteLine(i.ToString() + " " + Thread.CurrentThread.ManagedThreadId);
}));
}
Stopwatch watch = new Stopwatch();
watch.Start();
var final = Task.Factory.ContinueWhenAll(tasks.ToArray(), doneTasks =>
{
watch.Stop();
Console.WriteLine("done in {0}", watch.Elapsed);
});
Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)
我得到的输出:
100 24
100 23
...
100 14
100 25
done in 00:00:12.0044853
Run Code Online (Sandbox Code Playgroud)
我不明白为什么所有的我都是一样的,为什么100?直觉上我希望它们是0~99,但不是全部100.
我正在尝试创建一个函数,尝试在特定时间内异步连接到主机,然后检查是否已建立连接.
我的问题是我无法为此异步连接添加持续时间.
我的功能:
public async Task<bool> IsConnected()
{
// Host IP Address and communication port
string ipAddress = "192.168.0.11";
int port = 9100;
//Try to Connect with the host during 2 second
{
// Create TcpClient and try to connect
using (TcpClient client = new TcpClient())
{
Task<bool> mytask = client.ConnectAsync(ipAddress, port).Wait(TimeSpan.FromSeconds(2));
bool isconnected = await mytask;
if (isconnected)
{
//Connection with host
return true;
}
else
{
// No connection with host
return false;
}
//Close Connection
client.Close();
} …Run Code Online (Sandbox Code Playgroud) 我有以下任务,他们共享sum变量,最后总和应该是9,但我得到3.你能帮我解决一下吗?非常感谢.
int sum = 0;
Task t1 = Task.Factory.StartNew(() =>
{
sum = sum + Computation();
});
Task t2 = Task.Factory.StartNew(() =>
{
sum = sum + Computation();
});
Task t3 = Task.Factory.StartNew(() =>
{
sum = sum + Computation();
});
Task.WaitAll(t1, t2, t3);
Console.WriteLine($"The sum is {sum}");
private static int Computation()
{
return 3;
}
Run Code Online (Sandbox Code Playgroud) 任何人都可以向我解释这两种异步方法之间的区别吗?
方法A.
public async Task<List<Thumbnail>> GetAllThumbnailsAsync()
{
return await Task.Factory.StartNew(() =>
{
var imageUris = GetAllDirectoriesWithImageAsync(CommandBaseUri).Result;
return imageUris.Select(GetThumbnail).OrderByDescending(t => t.ImageDateTime).ToList();
});
}
Run Code Online (Sandbox Code Playgroud)
方法B.
public async Task<List<Thumbnail>> GetAllThumbnailsAsync()
{
var imageUris = await GetAllDirectoriesWithImageAsync(CommandBaseUri);
return imageUris.Select(GetThumbnail).OrderByDescending(t => t.ImageDateTime).ToList();
}
Run Code Online (Sandbox Code Playgroud)
据我所知,这两个方法都应该返回调用者并且不会阻止UI线程,但在这种情况下,只有方法A按预期工作,而方法B阻止我的UI.
我相信必须有一些基本概念,我可能在使用async/await时误解了.
任何人都可以开导我吗?
我有两个Task想要按顺序运行的对象.目前,我运行它们的代码如下所示:
private async Task Advance(IToken token, SyntaxKind kind)
{
await Approach(token);
await Surpass(token, kind);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,这是结合它们的最有效方法吗?我知道async涉及很多状态机逻辑,所以使用它会更有效ContinueWith吗?
private Task Advance(IToken token, SyntaxKind kind)
{
// TODO: This would take advantage of the overload accepting a state
// parameter to avoid the closure allocation
return Approach(token).ContinueWith(() => Surpass(token, kind));
}
Run Code Online (Sandbox Code Playgroud)
如果您认为它更有效,请随意指出另一种方法(既不是await也不是ContinueWith).谢谢.
注意:对于我的情况,我正在寻找结合两个非通用(无结果)Task的最好方法,但是为了谷歌遇到这个问题的人,可以Task<TResult>在你的答案中包括如何结合两个s.
我正在尝试使用System.Threading.Tasks.Task类实现并行处理.奇怪的是,任务委托执行在第一次方法调用时停止.我在下面编写示例代码以重新创建问题.
using System;
using System.Threading.Tasks;
namespace TestApp
{
public static class TestClass
{
static TestClass()
{
var tasks = new Task[Environment.ProcessorCount];
for (int i = 0; i < Environment.ProcessorCount; i++)
{
var task = Task.Run(() =>
{
Console.WriteLine("Start the Task " + i);
// Method Foo is not called.
// Stack trace show a managed to native transition.
// Why?
Foo(i);
});
tasks[i] = task;
}
Task.WaitAll(tasks);
Console.WriteLine("Press eny key to exit");
Console.ReadKey();
}
private static void Foo(int …Run Code Online (Sandbox Code Playgroud) 我有一个使用MEF加载插件的应用程序.所有这些插件都符合以下界面:
public interface IPlugin {
Task Start();
}
Run Code Online (Sandbox Code Playgroud)
所有方法都实现为async:public async Task Start()
当应用程序运行时,我有一个IEnumerable<IPlugin>可用于所有插件的属性.问题基本上是我如何Start()并行运行所有方法并等待所有方法完成?
我知道Parallel.ForEach(plugins, plugin => plugin.Start()),但这是不可能的,并且在所有插件启动之前执行仍在继续.
最有希望的解决方案似乎是Task.WhenAll(),但我不知道如何在不添加一些脚手架(这似乎是开销)的情况下将未知的方法列表发送到此.
我怎么能做到这一点?
task ×10
c# ×9
.net ×3
async-await ×3
asynchronous ×2
.net-4.6.2 ×1
.net-core ×1
api ×1
connection ×1
java ×1
queue ×1
tcpclient ×1