KiteWorks API 使用 HttpWebRequest 和 MultipartFormDataContent
KiteWorks API using HttpWebRequest and MultipartFormDataContent
jsonWebClient.DataContent = new System.Net.Http.MultipartFormDataContent();
ByteArrayContent bytes = new ByteArrayContent(File.ReadAllBytes(data.LocalFile));
bytes.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
jsonWebClient.DataContent.Add(bytes, "file", data.FileName);
jsonWebClient.DataContent.Add(bytes, "name", data.FileName);
jsonWebClient.DataContent.Add(new StringContent($"{Connection.UserId}"), "userId");
jsonWebClient.DataContent.Add(new StringContent($"{data.ParentId}"), "parentId");
jsonWebClient.DataContent.Add(new StringContent($"{fileInfo.CreationTime}"), "created");
jsonWebClient.DataContent.Add(new StringContent($"{fileInfo.LastWriteTime}"), "modified");
jsonWebClient.DataContent.Add(new StringContent($"{DateTime.Now}"), "clientCreated");
jsonWebClient.DataContent.Add(new StringContent($"{DateTime.Now}"), "clientModified");
jsonWebClient.DataContent.Add(new StringContent($"{fileInfo.Length}"), "size");
所以我正在尝试生成一个 MultipartFormDataContent 以转换为字节数组或流。当我做直播时:
Stream stream = _dataContent.ReadAsStreamAsync().Result;
我遇到内存不足异常。
当我尝试做的时候:
byte[] bytes = _dataContent.ReadAsByteArrayAsync().Result;
或
byte[] bytes = _dataContent.ReadAsByteArrayAsync().GetAwaiter().GetResult();
它只是永远坐在那里什么都不做。我该怎么做才能将其转换为正确的字节数组?
原始来源[我如何运行同步异步任务方法?][Rachel]How would I run an async Task<T> method synchronously?方法同步
public static class AsyncHelpers
{
/// <summary>
/// Execute's an async Task<T> method which has a void return value synchronously
/// </summary>
/// <param name="task">Task<T> method to execute</param>
public static void RunSync(Func<Task> task)
{
var oldContext = SynchronizationContext.Current;
var synch = new ExclusiveSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(synch);
synch.Post(async _ =>
{
try
{
await task();
}
catch (Exception e)
{
synch.InnerException = e;
throw;
}
finally
{
synch.EndMessageLoop();
}
}, null);
synch.BeginMessageLoop();
SynchronizationContext.SetSynchronizationContext(oldContext);
}
/// <summary>
/// Execute's an async Task<T> method which has a T return type synchronously
/// </summary>
/// <typeparam name="T">Return Type</typeparam>
/// <param name="task">Task<T> method to execute</param>
/// <returns></returns>
public static T RunSync<T>(Func<Task<T>> task)
{
var oldContext = SynchronizationContext.Current;
var synch = new ExclusiveSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(synch);
T ret = default(T);
synch.Post(async _ =>
{
try
{
ret = await task();
}
catch (Exception e)
{
synch.InnerException = e;
throw;
}
finally
{
synch.EndMessageLoop();
}
}, null);
synch.BeginMessageLoop();
SynchronizationContext.SetSynchronizationContext(oldContext);
return ret;
}
private class ExclusiveSynchronizationContext : SynchronizationContext
{
private bool done;
public Exception InnerException { get; set; }
readonly AutoResetEvent workItemsWaiting = new AutoResetEvent(false);
readonly Queue<Tuple<SendOrPostCallback, object>> items =
new Queue<Tuple<SendOrPostCallback, object>>();
public override void Send(SendOrPostCallback d, object state)
{
throw new NotSupportedException("We cannot send to our same thread");
}
public override void Post(SendOrPostCallback d, object state)
{
lock (items)
{
items.Enqueue(Tuple.Create(d, state));
}
workItemsWaiting.Set();
}
public void EndMessageLoop()
{
Post(_ => done = true, null);
}
public void BeginMessageLoop()
{
while (!done)
{
Tuple<SendOrPostCallback, object> task = null;
lock (items)
{
if (items.Count > 0)
{
task = items.Dequeue();
}
}
if (task != null)
{
task.Item1(task.Item2);
if (InnerException != null) // the method threw an exeption
{
throw new AggregateException("AsyncHelpers.Run method threw an exception.", InnerException);
}
}
else
{
workItemsWaiting.WaitOne();
}
}
}
public override SynchronizationContext CreateCopy()
{
return this;
}
}
}
有了这个class,我无需等待就可以立即转换它,并且没有内存不足异常的问题。
jsonWebClient.DataContent = new System.Net.Http.MultipartFormDataContent();
ByteArrayContent bytes = new ByteArrayContent(File.ReadAllBytes(data.LocalFile));
bytes.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
jsonWebClient.DataContent.Add(bytes, "file", data.FileName);
jsonWebClient.DataContent.Add(bytes, "name", data.FileName);
jsonWebClient.DataContent.Add(new StringContent($"{Connection.UserId}"), "userId");
jsonWebClient.DataContent.Add(new StringContent($"{data.ParentId}"), "parentId");
jsonWebClient.DataContent.Add(new StringContent($"{fileInfo.CreationTime}"), "created");
jsonWebClient.DataContent.Add(new StringContent($"{fileInfo.LastWriteTime}"), "modified");
jsonWebClient.DataContent.Add(new StringContent($"{DateTime.Now}"), "clientCreated");
jsonWebClient.DataContent.Add(new StringContent($"{DateTime.Now}"), "clientModified");
jsonWebClient.DataContent.Add(new StringContent($"{fileInfo.Length}"), "size");
所以我正在尝试生成一个 MultipartFormDataContent 以转换为字节数组或流。当我做直播时:
Stream stream = _dataContent.ReadAsStreamAsync().Result;
我遇到内存不足异常。
当我尝试做的时候:
byte[] bytes = _dataContent.ReadAsByteArrayAsync().Result;
或
byte[] bytes = _dataContent.ReadAsByteArrayAsync().GetAwaiter().GetResult();
它只是永远坐在那里什么都不做。我该怎么做才能将其转换为正确的字节数组?
原始来源[我如何运行同步异步任务方法?][Rachel]How would I run an async Task<T> method synchronously?方法同步
public static class AsyncHelpers
{
/// <summary>
/// Execute's an async Task<T> method which has a void return value synchronously
/// </summary>
/// <param name="task">Task<T> method to execute</param>
public static void RunSync(Func<Task> task)
{
var oldContext = SynchronizationContext.Current;
var synch = new ExclusiveSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(synch);
synch.Post(async _ =>
{
try
{
await task();
}
catch (Exception e)
{
synch.InnerException = e;
throw;
}
finally
{
synch.EndMessageLoop();
}
}, null);
synch.BeginMessageLoop();
SynchronizationContext.SetSynchronizationContext(oldContext);
}
/// <summary>
/// Execute's an async Task<T> method which has a T return type synchronously
/// </summary>
/// <typeparam name="T">Return Type</typeparam>
/// <param name="task">Task<T> method to execute</param>
/// <returns></returns>
public static T RunSync<T>(Func<Task<T>> task)
{
var oldContext = SynchronizationContext.Current;
var synch = new ExclusiveSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(synch);
T ret = default(T);
synch.Post(async _ =>
{
try
{
ret = await task();
}
catch (Exception e)
{
synch.InnerException = e;
throw;
}
finally
{
synch.EndMessageLoop();
}
}, null);
synch.BeginMessageLoop();
SynchronizationContext.SetSynchronizationContext(oldContext);
return ret;
}
private class ExclusiveSynchronizationContext : SynchronizationContext
{
private bool done;
public Exception InnerException { get; set; }
readonly AutoResetEvent workItemsWaiting = new AutoResetEvent(false);
readonly Queue<Tuple<SendOrPostCallback, object>> items =
new Queue<Tuple<SendOrPostCallback, object>>();
public override void Send(SendOrPostCallback d, object state)
{
throw new NotSupportedException("We cannot send to our same thread");
}
public override void Post(SendOrPostCallback d, object state)
{
lock (items)
{
items.Enqueue(Tuple.Create(d, state));
}
workItemsWaiting.Set();
}
public void EndMessageLoop()
{
Post(_ => done = true, null);
}
public void BeginMessageLoop()
{
while (!done)
{
Tuple<SendOrPostCallback, object> task = null;
lock (items)
{
if (items.Count > 0)
{
task = items.Dequeue();
}
}
if (task != null)
{
task.Item1(task.Item2);
if (InnerException != null) // the method threw an exeption
{
throw new AggregateException("AsyncHelpers.Run method threw an exception.", InnerException);
}
}
else
{
workItemsWaiting.WaitOne();
}
}
}
public override SynchronizationContext CreateCopy()
{
return this;
}
}
}
有了这个class,我无需等待就可以立即转换它,并且没有内存不足异常的问题。