我是.net中的Threading的新手,我正在维护一个用MVC 5编写的应用程序。 该应用程序有一个静态Utility类,它有一个静态PostRequests方法来处理Web客户端请求。 在网页上,我启动了3个线程,它们将调用此静态方法从3个不同的源获取数据。
每个Webclient请求的超时时间为45秒。但其中一个线程只打印约30秒的日志,并在没有完成工作的情况下死亡。 我阅读了一些文章,其中写了引用变量需要使线程安全,我不知道该怎么做。 我的问题是: 方法线程安全吗?我在参数或访问变量的某个地方犯了错误吗?
这是方法
private static Stopwatch timer = new Stopwatch();
public static List<T> PostRequests<T>(string url, string querystring, Request request) where T : IResponse
{
try
{
if (string.IsNullOrWhiteSpace(querystring))
querystring = "?apikey=" + AppSettings.APIAccessKey;
else
querystring = querystring + "&apikey=" + AppSettings.APIAccessKey;
var timestamp = string.Format("{0:dd/MM/yyyy HH:mm}", DateTime.UtcNow);
WsfWebClient client = new WsfWebClient();
var headers = new WebHeaderCollection();
headers.Add("timestamp", timestamp);
headers.Add("Content-Type", "application/json");
var message = Signer.BuildMessage(url, "POST", HttpUtility.ParseQueryString(querystring), timestamp);
var signature = Signer.ComputeHash(AppSettings.APISecretKey, message);
headers.Add("signature", signature);
client.Headers = headers;
var json = request.ToJsonString();
Logger.Debug(String.Format("SDK: Posting data to the API. JSON: {0}", json));
timer.Start();
var response = client.UploadData(AppSettings.APIUrl + url + querystring, "POST", Encoding.Default.GetBytes(json));
timer.Stop();
Logger.Info(string.Format("Time Spent for : WSF Call - {0}", timer.Elapsed.Milliseconds.ToString()));
return ParseListResponse<T>(Encoding.Default.GetString(response));
}
catch (Exception ex)
{
Logger.Error("SDK: Post Request to Builder API failed.", ex, typeof(Utilities));
var responseObject = GetInstance<List<T>>();
if (responseObject.Count > 0)
{
responseObject[0].GenerateError("", "Post Request to Builder API failed.", ex.StackTrace);
}
return responseObject;
}
}
public class WsfWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest request = base.GetWebRequest(uri);
// Set timeout for 45 seconds
request.Timeout = AppSettings.WsfWebClientTimeOut;
return request;
}
}