TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Andrew Harkins
NA
21
795
C# Method being called multiple times but locking it for only 1 execut
Aug 16 2020 8:10 PM
Hello every1,
I have some code that is connected to a websocket. And it can execute less than .0005 ms so it can be called basically instantly multiple times. I can only let this code execute once at a time. After the code finishes executing it can then execute again. I have tried using a lock statement, using a Counter, and switching many different parts of code around to make this happen properly. I got the code functioning how I want it to, or at least I think I do.. its working for now, I created a TradeDelay method but I know it this code is not setup properly and I would to learn proper implementation. I believe I should be able to completely remove this TradeDelay() and my ‘Counter’ once I have everything setup correctly.
public
partial
class
MainWindow : Window
{
static
readonly
object
lockIt =
new
object
();
private
void
TurnOnSocket(){
var incoming = SocketClient.SubscribeToTradeUpdatesAsync(
"BTCUSD"
,(data) =>
{
if
((tExecute ==
null
) || !tExecute.Status.Equals(TaskStatus.Running))
{
ExecuteTradeDelay();
//lock (lockIt)
//{
// // if(counterExecute == 0)
// // {
// // counterExecute++;
// ExecuteTradeAsync();
// // }
// //}
//}
_ = AddNewIncomingTradeAsync(data);
//counterExecute = 0;
// AddNewTrade(data);
// UpdateLstIncoming();
// tradingClient.AddNewTrade(data);
}
}
}
private
async Task ExecuteTradeDelay()
{
await Task.Delay(1500);
lock
(lockIt)
{
if
(counterExecute == 0)
{
counterExecute++;
_ = ExecuteTradeAsync();
}
}
await Task.Delay(2500);
counterExecute = 0;
}
private
async Task ExecuteTradeAsync()
{
cancelExecute =
new
CancellationTokenSource();
//if (counterExecute == 0) //{
//counterExecute++;
if
(running)
{
//lock (lockSafe) //{
tExecute = Task.Factory.StartNew(async () =>
{
try
{
if
(!did1B)
{
if
(ActiveTrades.ContainsKey(
"Trade1B"
))
{
if
(UnsureWhyPriceValid(Convert.ToDecimal(CurrentPrice.Price), ActiveTrades[
"Trade1B"
].StopPrice))
{
StopOrder stopOrder =
new
StopOrder(ActiveTrades[
"Trade1B"
].TradeSymbol, ActiveTrades[
"Trade1B"
].StopPrice, ActiveTrades[
"Trade1B"
].LimitPrice, ActiveTrades[
"Trade1B"
].CryptoAmount);
var placedOrder = await tradingClient.StopOrderBuyAsyncV2(stopOrder).ConfigureAwait(
false
);
AddTradeStatusList(placedOrder,
"Trade1B"
);
HarkinsLogger.Log(
"Trade 1 - Buy Executed & added to 'TradeStatusList'"
);
trade1B =
false
;
ActiveTrades.Remove(
"Trade1B"
);
_ = PrintActiveTradesAsync();
return
;
}
}
}
}
}
Reply
Answers (
0
)
Taxi Booking Database
How to set Asp.net core3.0 Cookies as Secure