using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ThreadsTests
{
public class WorkData
{
public int Id;
}
public abstract class ProtoBase<T>
{
private static int NextId;
private TaskCompletionSource<T> _dataTaskCompletionSource = new TaskCompletionSource<T>();
public int give_count = 1;
protected ProtoBase()
{
Id = ++NextId;
new Task(Parse).Start();
}
public int Id { get; }
public bool IsFinish { get; private set; }
protected void Finish()
{
IsFinish = true;
}
public async Task PushData(T data)
{
_dataTaskCompletionSource.SetResult(data);
await Task.Yield();
}
protected async Task<T> GetNextData()
{
var taskResult = await _dataTaskCompletionSource.Task;
_dataTaskCompletionSource = new TaskCompletionSource<T>();
return taskResult;
}
protected abstract void Parse();
}
public class TestWorker : ProtoBase<WorkData>
{
protected override async void Parse()
{
WorkData data = await GetNextData();
Trace.TraceInformation("{0:N0} take 1 [id={1:N0}]", Id, data.Id);
data = await GetNextData();
Trace.TraceInformation("{0:N0} take 2 [id={1:N0}]", Id, data.Id);
data = await GetNextData();
Trace.TraceInformation("{0:N0} take 3 [id={1:N0}]", Id, data.Id);
Finish();
Trace.TraceInformation("{0:N0} Finish ххх", Id);
}
}
public class Program
{
public static async Task Main(string[] args)
{
var schedulerPair = new ConcurrentExclusiveSchedulerPair();
await await Task.Factory.StartNew(
AsyncWorkersTest,
CancellationToken.None,
TaskCreationOptions.None,
schedulerPair.ExclusiveScheduler);
Console.WriteLine("FINISHED");
Console.ReadKey();
}
public static async Task AsyncWorkersTest()
{
//workers count
const int testCount = 1000; // 100, 1000, 10000, 100000
var Workers = new List<TestWorker>();
for (int i = 0; i < testCount; i++)
{
Workers.Add(new TestWorker());
}
Random rnd = new Random();
int getDataCount = testCount * 3;
for (int i = 0; i < getDataCount; i++)
{
int ind = rnd.Next(0, Workers.Count);
WorkData wd = new WorkData() { Id = i };
if (Workers[ind].IsFinish) continue;
Trace.TraceInformation("{0:N0} push {1} [id={2:N0}]", Workers[ind].Id, Workers[ind].give_count++, wd.Id);
await Workers[ind].PushData(wd);
}
}
}
}
ConsoleApp1 Information: 0 : 1 push 1 [id=0]
ConsoleApp1 Information: 0 : 1 take 1 [id=0]
ConsoleApp1 Information: 0 : 2 push 1 [id=1]
ConsoleApp1 Information: 0 : 2 take 1 [id=1]
ConsoleApp1 Information: 0 : 1 push 2 [id=2]
ConsoleApp1 Information: 0 : 1 take 2 [id=2]
ConsoleApp1 Information: 0 : 1 push 3 [id=3]
ConsoleApp1 Information: 0 : 1 take 3 [id=3]
ConsoleApp1 Information: 0 : 1 Finish ххх
ConsoleApp1 Information: 0 : 2 push 2 [id=4]
ConsoleApp1 Information: 0 : 2 take 2 [id=4]
ConsoleApp1 Information: 0 : 2 push 3 [id=5]
ConsoleApp1 Information: 0 : 2 take 3 [id=5]
ConsoleApp1 Information: 0 : 2 Finish ххх
private async Task<string> jsexec()
{
string script = "$('.page_title').text()";
var response = await chromeBrowser.EvaluateScriptAsync(script);
if (response.Success && response.Result != null)
{
var result = response.Result.ToString();
MessageBox.Show(result);
return result;
}
else
{
return null;
}
}
<Label
Content="{Binding ElementName=slider1, Path=Value}"
ContentStringFormat="{}Выбрано {0} единиц"
DockPanel.Dock="Top"
/>
using (var reader = new BinaryReader(File.Open("<file path>", FileMode.Open)))
{
var value1 = reader.ReadDouble();
var value2 = reader.ReadDouble();
...
}
using (var bw = new BinaryWriter(File.Create("<file path>")))
{
double value1 = 2;
double value2 = 17950.015625;
bw.Write(value1);
bw.Write(value2);
}
public sealed class ProgressChangedEventArgs : EventArgs
{
public ProgressChangedEventArgs (int progress) { this.Progress = progress; }
public int Progress { get; }
}
public event EventHandler<ProgressChangedEventArgs> StatusStripProgressChanged;
private void RaiseStatusStripProgressChanged(int progress)
{
StatusStripProgressChanged?.Invoke(new ProgressChangedEventArgs(progress));
}
public interface ISignable
{
ISignature Signature { get; set; }
byte[] Serialize();
}
public interface ISignature
{
}
public interface ISignatureService
{
bool Validate(ISignable signable);
void Sign(ISignable signable);
}
class MyObject : ISignable
{
public ISignature Signature { get; set; }
public long Param1 { get; set; }
public string Param2 { get; set; }
public string InnerData { get; set; }
public byte[] Serialize()
{
return Encoding.UTF8.GetBytes(Param1 + Param2 + InnerData);
}
}
public class HashCodeSignatureService : ISignatureService
{
public void Sign(ISignable signable)
{
var signature = CalculateSignature(signable);
signable.Signature = signature;
}
public bool Validate(ISignable signable)
{
var s1 = CalculateSignature(signable);
var s2 = signable.Signature as SimpleHashCodeSignature;
return s1?.HashCode == s2?.HashCode;
}
private static SimpleHashCodeSignature CalculateSignature(ISignable signable)
{
var body = signable.Serialize();
var signature = new SimpleHashCodeSignature(body.Aggregate(0, (a, b) => a + b.GetHashCode()));
return signature;
}
}
public class SimpleHashCodeSignature : ISignature
{
public int HashCode { get; }
public SimpleHashCodeSignature(int hashCode)
{
HashCode = hashCode;
}
}
class Program
{
static void Main(string[] args)
{
var obj = new MyObject {Param1 = 1, Param2 = "asd", InnerData = "some data"};
var signatureService = new HashCodeSignatureService();
signatureService.Sign(obj);
// Passing the object across untrusted boundary
signatureService.Validate(obj);
}
}
for (int i = 0; i < taskCount; i++)
{
Thread thread = new Thread(ParsingDocUserIdAync);
p[1] = docStarId;
p[2] += (int)offset;
thread.Start(param);
docStarId = p[2]+1;
list.Add(thread);
}
p
и param
- суть один и тот же объект). thread.Start(param)
не гарантирует, что поток создастся и начнёт выполняться моментально. class Program
{
static void Main(string[] args)
{
string scriptFileName = Path.GetTempFileName() + ".cs";
var scriptBody = GenerateScript(scriptFileName);
var script = CSharpScript.Create(
scriptBody,
globalsType: typeof(Globals),
options: ScriptOptions
.Default
.WithEmitDebugInformation(true)
.WithFilePath(scriptFileName)
.WithFileEncoding(Encoding.UTF8));
var sum = script.RunAsync(new Globals {X = 56, Y = 42}).Result.ReturnValue;
Console.Out.WriteLine(sum);
Console.ReadKey();
File.Delete(scriptFileName);
}
private static string GenerateScript(string fileName)
{
var body =
@"var result = X + Y;
return result;
";
File.WriteAllText(fileName, body, Encoding.UTF8);
return body;
}
}
public class Globals
{
public int X { get; set; }
public int Y { get; set; }
}