I'm working on a .NET Core app which uses Google Sheets Api. I'm using async tasks to avoid freezing guis. My trouble starts here. These async tasks connect Google Sheets and return some values. One of tasks:
public async Task<String> KullaniciBilgileriniAl()
{
String range = "Kullanici Bilgileri";
SpreadsheetsResource.ValuesResource.GetRequest request = this.service.Spreadsheets.Values.Get(spreadsheetId, range);
ValueRange response = await Task.Run(() => request.Execute());
IList<IList<Object>> values = response.Values;
String DataKullaniciAdi = (String) values[1][0];
String DataSifre = (String)values[1][1];
return DataKullaniciAdi DataSifre;
}
What i'm trying to do is catch exceptions if there's no internet connection. If there's no connection, errors accure on this line:
ValueRange response = await Task.Run(() => request.Execute());
I've tried add this line into try-catch statement like that:
try
{
ValueRange response = await Task.Run(() => request.Execute());
IList<IList<Object>> values = response.Values;
String DataKullaniciAdi = (String)values[1][0];
String DataSifre = (String)values[1][1];
return DataKullaniciAdi DataSifre;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
but tasks run on different threads. So it didn't work.
In summary, i need to catch any exception which accures in Task.Run() function. How can i do that?
CodePudding user response:
Well first of all remove Task.Run
as it serves no purpose. You are create a task to run a synchronous method which is not needed. However, if you really want to keep it there for whatever reason, catch the exception within the task:
ValueRange response = await Task.Run(() => {
try {
return request.Execute();
} catch Exception(Exception e){
return null;
}
});