Reputation: 7746
I have a function apiClient.OrderSend
that must be called inside the "GUI" thread, so I created this function
private void RunOnUIThread(Action action)
{
this.BeginInvoke(action);
}
I then have a function that needs to return
an int
like this
int AlgoSendOrder(MT4Order order)
{
int retVal = -1;
RunOnUIThread(() =>
{
retVal = apiClient.OrderSend(order.Symbol, (TradeOperation)order.OrderSide, order.Volume,
order.Price, order.AllowedSlippage ?? default(int),
order.PriceToStopLoss ?? default(double),
order.PriceToTakeProfit ?? default(double));
});
return retVal;
}
The problem is that AlgoSendOrder
returns before apiClient.OrderSend
returns, so retVal
is always -1 to the client of this function.
It seems that this a reasonable change is to use await-async
pair execute the function in the GUI thread, and to have the desired effect of waiting for the return value. However I can't seem to get it to work.
Seems like I should be able to rework RunOnUIThread
to use async-await
public async Task RunOnUIThreadAsync()
{
if (InvokeRequired)
{
// what do I put here?
}
{
… // like before (but can now use `await` expressions)
}
}
Upvotes: 3
Views: 4596
Reputation: 4418
Use an async method to perform the background task in a separate thread. Note the Task.Run in the sample below:
async Task<int> AlgoSendOrderAsync(MT4Order order)
{
int retVal = -1;
//Doing this on another thread using Task.Run
await Task.Run(() =>
{
retVal = apiClient.OrderSend(order.Symbol, (TradeOperation)order.OrderSide, order.Volume,
order.Price, order.AllowedSlippage ?? default(int),
order.PriceToStopLoss ?? default(double),
order.PriceToTakeProfit ?? default(double));
});
return retVal;
}
Call this method on the UI thread like this:
async void onButtonClickOnWhatever(object sender, EventArgs args)
{
int result = await AlgoSendOrderAsync(order);
//Here you are on the UI thread, you can update your controls here safely
}
Upvotes: 5