我有一个程序可以将文件上传/下载到在线服务器上,有一个回调来报告进度并将其记录到文本文件中。该程序使用以下结构构建:
public void Upload(string source, string destination)
{
//Object containing Source and destination to pass to the threaded function
KeyValuePair<string, string> file = new KeyValuePair<string, string>(source, destination);
//Threading to make sure no blocking happens after calling upload Function
Thread t = new Thread(new ParameterizedThreadStart(amazonHandler.TUpload));
t.Start(file);
}
private void TUpload(object fileInfo)
{
KeyValuePair<string, string> file = (KeyValuePair<string, string>)fileInfo;
/*
Some Magic goes here,Checking The file and Authorizing Upload
*/
var ftiObject = new FtiObject ()
{ FileNameOnHDD = file.Key,
DestinationPath = file.Value,
//Has more data used for calculations.
};
//Threading to make sure progress gets callback gets called.
Thread t = new Thread(new ParameterizedThreadStart(amazonHandler.UploadOP));
t.Start(ftiObject);
//Signal used to stop progress untill uploadCompleted is called.
uploadChunkDoneSignal.WaitOne();
/*
Some Extra Code
*/
}
private void UploadOP(object ftiSentObject)
{
FtiObject ftiObject = (FtiObject)ftiSentObject;
/*
Some useless code to create the uri and prepare the ftiObject.
*/
// webClient.UploadFileAsync will open a thread that
// will upload the file and report
// progress/complete using registered callback functions.
webClient.UploadFileAsync(uri, "PUT", ftiObject.FileNameOnHDD, ftiObject);
}
我收到了一个注册到Webclient的UploadProgressChanged事件的回调,但每次发送的请求都会被调用两次。
void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e)
{
FtiObject ftiObject = (FtiObject )e.UserState;
Logger.log(ftiObject.FileNameOnHDD, (double)e.BytesSent ,e.TotalBytesToSend);
}
日志输出:
Filename: C:\Text1.txt Uploaded:1024 TotalFileSize: 665241
Filename: C:\Text1.txt Uploaded:1024 TotalFileSize: 665241
Filename: C:\Text1.txt Uploaded:2048 TotalFileSize: 665241
Filename: C:\Text1.txt Uploaded:2048 TotalFileSize: 665241
Filename: C:\Text1.txt Uploaded:3072 TotalFileSize: 665241
Filename: C:\Text1.txt Uploaded:3072 TotalFileSize: 665241
Etc...
我正在使用观察者观看网络流量,并且只发送了1个请求。
有些我怎么不能弄清楚为什么回调被调用两次,我怀疑是回调是被每个线程打开(主要上传和TUpload),但是我不知道如何测试这是否是原因
注意:许多/ ** / Comments背后的原因是表明函数不仅仅是打开线程,而且正在使用线程来确保不会发生阻塞(有几个“Signal.WaitOne() “围绕同步代码”
答案 0 :(得分:1)
如果你在回调上设置断点,你不能检查callstack以查看来电的来源吗?如果您使用的是Visual Studio。
答案 1 :(得分:1)
您是否在上传ProgressChangedEventArgs中检查了API确实没有使用不同信息回调两次?