我有一个超过 10k 项的 deviceList,想通过调用另一种方法发送数据。
我尝试使用 Parallel.Foreach 但我不确定这是正确的方法。
我已经在 azure 上发布了这个 webapp,我已经测试了 100 次它工作正常,但是对于 10k 次它有超时问题。我的实现是否需要任何调整,谢谢
private List<Task> taskEventList = new List<Task>();
public async Task ProcessStart()
{
string messageData = "{\"name\":\"DemoData\",\"no\":\"111\"}";
RegistryManager registryManager;
Parallel.ForEach(deviceList, async (device) =>
{
// get details for each device and use key to send message
device = await registryManager.GetDeviceAsync(device.DeviceId);
SendMessages(device.DeviceId, device.Key, messageData);
});
if (taskEventList.Count > 0)
{
await Task.WhenAll(taskEventList);
}
}
private void SendMessages(string deviceId, string Key, string messageData)
{
DeviceClient deviceClient = DeviceClient.Create(hostName, new …Run Code Online (Sandbox Code Playgroud) 我有方法,要检查房东的数目?房东类型
我有这段代码来检查它
var type = _landlordTypeRepository.GetAll()
.Include(x => x.Landlords)
.FirstOrDefault(x => x.Id == input.Id);
if (type.Landlords.Count > 0)
{
throw new UserFriendlyException(L("ThisTypeIsInUse"));
}
Run Code Online (Sandbox Code Playgroud)
但是我这样改写了
var type = _landlordTypeRepository
.GetAll()
.AnyAsync(x=> x.Id == input.Id && x.Landlords.Any());
Run Code Online (Sandbox Code Playgroud)
但是现在返回类型ID Task<bool>
如果我该如何使用呢?
public void SynchronousFunction(/* some input */) { /* some synchronous operation */}
// VS
public Task SynchronousFunction(/* some input */)
{
/* some synchronous operation */
return Task.CompletedTask
}
// VS Variation of Task return function
public Task SynchronousFunction(/* some input */)
{
return Task.Run(() => /* some synchronous operation */
}
Run Code Online (Sandbox Code Playgroud)
我的观点有两点。首先,感觉返回任务需要一些不必要的装箱和拆箱,其次,如果在某些同步代码中调用该函数,则不需要使用 .Wait() 或类似的东西来调用。
Parallel.For中有这个错误吗?
public class DataPoint
{
public int Game { get; set; }
public byte Card { get; set; }
public byte Location { get; set; }
public DataPoint(int g,byte c,byte Loc)
{
Game = g;
Card = c;
Location = Loc;
}
public override string ToString()
{
return String.Format("{0} {1} {2}",Game,Card,Location);
}
}
Run Code Online (Sandbox Code Playgroud)
它必须是Parallel.For中的错误
private static System.Collections.Concurrent.ConcurrentBag<DataPoint> FillData()
{
var points = new System.Collections.Concurrent.ConcurrentBag<DataPoint>();
long c = 32768;
long z = 0;
Parallel.For(z, c, (i) =>
{
points.Add(new DataPoint( rand.Next(1, …Run Code Online (Sandbox Code Playgroud) 前几天我遇到了这段代码:
Task.Factory.StartNew(() =>
{
d1();
}).ContinueWith((_) =>
{
d2();
}).ContinueWith((_) =>
{
d3();
});
Run Code Online (Sandbox Code Playgroud)
我有什么理由不能将其重构到下面吗?
Task.Factory.StartNew(() =>
{
d1();
d2();
d3();
});
Run Code Online (Sandbox Code Playgroud) 好吧,我开始写一个非常大的应用程序.
将有许多多线程函数.
据我所知,所有任务都在主线程(ui线程)下运行.
但我看到许多经验丰富的.net开发人员建议使用任务而不是线程.
所以我对是否应该使用线程或任务感到困惑?
有这么多任务会阻塞主线程(ui)吗?
新任务启动示例
Task.Factory.StartNew(() =>
{
myfunction();
});
Run Code Online (Sandbox Code Playgroud)
这些类型的新任务是否可以阻止主线程或使其变重?
我的第二个问题
下面的类和函数是在主线程下创建的
public static class PublicStaticFunctions
{
public static MTObservableCollection<string> ocEventsCollection = new MTObservableCollection<string>();
private static readonly object _locker_ocEventsCollection = new object();
public static void AddMsgToEvents(string srMessage)
{
lock (_locker_ocEventsCollection)
ocEventsCollection.Insert(0, srMessage + " - Time: " + DateTime.Now.TimeOfDay.ToString().Split('.')[0]);
}
}
Run Code Online (Sandbox Code Playgroud)
我使用_locker_ocEventsCollection来锁定.这个线程在任务中是否安全?我的意思是即使它们处于不同的线程下它仍然是线程安全的吗?
1更多问题 - 问题3
如何从自身取消匿名启动的任务
我的意思是上面的例子myfunction(); 是作为一项任务开始的
在myfunction()中; 我想在某些操作完成后取消该特定任务
我怎样才能实现这一目标?
例如
private void myfunction ()
{
//some operation
Cancelthistask // how ?
}
Run Code Online (Sandbox Code Playgroud) 我无法找到正确的语法,以便使用await with lambda表达式(匿名lambda方法).所有示例似乎都使用了使用async关键字声明的实际方法.让我来描述我想要的东西:
...code in UI thread...
Customer cust = null;
using (DataContext context = new DataContext()) // I want to run this async
{
cust = context.Customers.Single(c => c.Id == 1);
}
...continue code in UI thread...
Run Code Online (Sandbox Code Playgroud)
为了在数据库查询期间不阻塞UI线程,我会写:
...code in UI thread...
Customer cust = null;
Task.Run(() =>
{
using (DataContext context = new DataContext())
{
cust = context.Customers.Single(c => c.Id == 1);
}
});
...continue code in UI thread...
Run Code Online (Sandbox Code Playgroud)
当然,这不起作用,因为UI线程将在任务启动后继续.我不能Wait()上Task,因为这会阻止用户界面线程.简单地await在前面添加Task.Run()不编译.我能想到的最好的事情是: …
此代码取自其他网站:
using System;
using System.Threading.Tasks;
public class Program {
private static Int32 Sum(Int32 n)
{
Int32 sum = 0;
for (; n > 0; n--)
checked { sum += n; }
return sum;
}
public static void Main() {
Task<int32> t = new Task<int32>(n => Sum((Int32)n), 1000);
t.Start();
t.Wait();
// Get the result (the Result property internally calls Wait)
Console.WriteLine("The sum is: " + t.Result); // An Int32 value
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白使用私有静态方法的目的,而不是任何其他正常的公共方法.
谢谢
我有一系列Tasks,我想从az顺序运行.
我想同步执行这些调用starting from 1 and ending at N.
这是代码的样子
public async Task DeleteProject(Project project)
{
var deleteSubProjects = …Run Code Online (Sandbox Code Playgroud) 当我调用BuildCustomer.StartTask时,我调用一个方法WriteToDatabase.在WriteToDatabase内部,我想将状态发送回MainForm以将状态写入GUI.当代码到达那一点时,我的应用程序冻结并且没有错误.我确实发现如果我删除task.Wait(),它会停止冻结并运行.但我想我想要等待,因为我的BuildCustomer需要一些时间并将大量更新(包括来自Common类的更多更新)写入GUI.有人可以告诉我什么是错的或我应该采取哪些不同的做法?这是一个.Net 4项目,所以我不能使用async,我已经看到了其他答案.
public partial class MainForm : Window
{
public MainForm()
{
Common.SendMessage += UpdateStatus;
}
private void Button_Click(object sender, EventArgs e)
{
BuildCustomer.StartTask();
}
private void UpdateStatus(string message)
{
Dispatcher.Invoke(new Action(() =>
{
StatusTextBox.Text = message;
}));
}
}
public class BuildCustomer
{
public static void StartTask()
{
var action = new Action<object>(BuildCustomer);
var task = new Task(() => action(buildDetails));
task.Start();
task.Wait();
}
private void BuildCustomerDetails(object buildDetails)
{
Common.WriteToDatabase();
}
}
public class Common
{
public delegate void MessageLogDelegate(string …Run Code Online (Sandbox Code Playgroud) 可以Task用作字典键还是一个坏主意?任何可能因此而出现的问题?
抱歉标题不好.我目前正在学习TPL并阅读这篇博客文章
异步调用同步方法的能力对可伸缩性没有任何作用,因为如果你同步调用它,你通常仍会消耗相同数量的资源(事实上,你使用的更多,因为它有开销因安排某事而招致).
所以我想让我们尝试一下,然后我创建了使用WebClient's DownloadStringTaskAsync和DownloadString(同步)方法的演示应用程序.
我的演示应用程序有两种方法
DownloadHtmlNotAsyncInAsyncWay
这提供了围绕同步方法的异步方法包装器,DownloadString它不应该扩展良好.
DownloadHTMLCSAsync
这会调用异步方法DownloadStringTaskAsync.
我从两种方法中创建了100个任务并比较了消耗的时间,发现选项1比第二个消耗的时间少.为什么?
这是我的代码.
using System;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;
public class Program
{
public static void Main()
{
const int repeattime = 100;
var s = new Sample();
var sw = new Stopwatch();
var tasks = new Task<string>[repeattime];
sw.Start();
for (var i = 0; i < repeattime; i++)
{
tasks[i] = s.DownloadHtmlNotAsyncInAsyncWay();
}
Task.WhenAll(tasks);
Console.WriteLine("==========Time elapsed(non natural async): " + sw.Elapsed …Run Code Online (Sandbox Code Playgroud) c# ×12
async-await ×4
.net ×2
asynchronous ×1
c#-5.0 ×1
dictionary ×1
performance ×1
task ×1
wpf ×1