Новичок в программировании в C# (пришла из Java) и пытается познакомиться с методологиями C#, лежащих в основе многопоточного.public class AppSynchronizationContext : System.Threading.SynchronizationContext
{
private readonly ConcurrentQueue future = new ConcurrentQueue();
private struct FutureInvocation
{
private readonly SendOrPostCallback sendOrPostCallback;
private readonly object state;
private readonly WaitHandle waitHandle;
public FutureInvocation(SendOrPostCallback s, object st, WaitHandle waitHandle)
{
sendOrPostCallback = s;
state = st;
this.waitHandle = waitHandle;
}
public SendOrPostCallback SendOrPostCallback
{
get
{
return sendOrPostCallback;
}
}
public object State
{
get
{
return state;
}
}
public WaitHandle WaitHandle
{
get
{
return waitHandle;
}
}
}
/*
* Periodically polled on the main app thread.
* */
public void Poll()
{
DateTime t = DateTime.Now;
int timeOut = 1500;
while (!future.IsEmpty)
{
FutureInvocation f;
if (future.TryDequeue(out f))
{
f.SendOrPostCallback?.Invoke(f.State);
if (f.WaitHandle != null)
{
AutoResetEvent e = (AutoResetEvent)f.WaitHandle;
e.Set();
}
}
if((DateTime.Now - t).Milliseconds >= timeOut)
{
//If the elapsed time is >= timeout seconds, break and allow the main thread to continue (Other queued items will be done on next poll)
break;
}
}
}
/*
* Should block until SendOrPosTCallback completes, per my understanding
* */
public override void Send(SendOrPostCallback d, object state)
{
WaitHandle w = new AutoResetEvent(false);
FutureInvocation f = new FutureInvocation(d, state, w);
future.Enqueue(f);
//Block here.
w.WaitOne();
}
/* Something goes here...*/
public override void OperationCompleted()
{
base.OperationCompleted();
}
/* Something goes here...*/
public override void OperationStarted()
{
base.OperationStarted();
}
/*
*
* Add it to the queue without worrying about if the callback has completed..
* */
public override void Post(SendOrPostCallback d, object state)
{
FutureInvocation f = new FutureInvocation(d, state, null);
future.Enqueue(f);
}
/*
* Creates a deep copy of the existing Synchronization Context.
* */
public override SynchronizationContext CreateCopy()
{
AppSynchronizationContext s = new AppSynchronizationContext();
foreach(FutureInvocation f in future)
{
s.future.Enqueue(f);
}
return s;
}
}
< /code>
У меня есть несколько вопросов, касающихся реализации синхронизации. И операция, складываемая, какова их цель и как я могу их реализовать?
Подробнее здесь: https://stackoverflow.com/questions/476 ... tioncomple